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 |
|---|---|---|---|---|
about.tsx | import '../src/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/styles';
import Link from 'next/link';
const useStyles = makeStyles(theme => ({
root: {
textAlign: 'center',
paddingTop: theme.spacing.unit * 20,
},
}));
function About() |
export default About;
| {
const classes = useStyles({});
return (
<div className={classes.root}>
<Typography variant="h4" gutterBottom>
Material-UI
</Typography>
<Typography variant="subtitle1" gutterBottom>
about page
</Typography>
<Typography gutterBottom>
<Link href="/">
<a>Go to the main page</a>
</Link>
</Typography>
<Button variant="contained" color="primary">
Do nothing button
</Button>
</div>
);
} | identifier_body |
_hasidof.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#------------------------------------------------------------------------- | _ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import HasGrampsId
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class HasIdOf(HasGrampsId):
"""Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID") | #
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale | random_line_split |
_hasidof.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import HasGrampsId
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class | (HasGrampsId):
"""Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID")
| HasIdOf | identifier_name |
_hasidof.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .. import HasGrampsId
#-------------------------------------------------------------------------
#
# HasIdOf
#
#-------------------------------------------------------------------------
class HasIdOf(HasGrampsId):
| """Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID") | identifier_body | |
utils.py | # -*- coding: utf-8 -*-
# gedit CodeCompletion plugin
# Copyright (C) 2011 Fabio Zendhi Nagao
#
# 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/>.
def get_word(piter):
a = piter.copy()
b = piter.copy()
while True:
if a.starts_line():
break
a.backward_char()
ch = a.get_char()
#if not (ch.isalnum() or ch in ['_', ':', '.', '-', '>']):
if not (ch.isalnum() or ch in "_:.->"):
a.forward_char()
break
|
def get_document(piter):
a = piter.copy()
b = piter.copy()
while True:
if not a.backward_char():
break
while True:
if not b.forward_char():
break
return a.get_visible_text(b)
# ex:ts=4:et: | word = a.get_visible_text(b)
return a, word | random_line_split |
utils.py | # -*- coding: utf-8 -*-
# gedit CodeCompletion plugin
# Copyright (C) 2011 Fabio Zendhi Nagao
#
# 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/>.
def get_word(piter):
|
def get_document(piter):
a = piter.copy()
b = piter.copy()
while True:
if not a.backward_char():
break
while True:
if not b.forward_char():
break
return a.get_visible_text(b)
# ex:ts=4:et:
| a = piter.copy()
b = piter.copy()
while True:
if a.starts_line():
break
a.backward_char()
ch = a.get_char()
#if not (ch.isalnum() or ch in ['_', ':', '.', '-', '>']):
if not (ch.isalnum() or ch in "_:.->"):
a.forward_char()
break
word = a.get_visible_text(b)
return a, word | identifier_body |
utils.py | # -*- coding: utf-8 -*-
# gedit CodeCompletion plugin
# Copyright (C) 2011 Fabio Zendhi Nagao
#
# 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/>.
def | (piter):
a = piter.copy()
b = piter.copy()
while True:
if a.starts_line():
break
a.backward_char()
ch = a.get_char()
#if not (ch.isalnum() or ch in ['_', ':', '.', '-', '>']):
if not (ch.isalnum() or ch in "_:.->"):
a.forward_char()
break
word = a.get_visible_text(b)
return a, word
def get_document(piter):
a = piter.copy()
b = piter.copy()
while True:
if not a.backward_char():
break
while True:
if not b.forward_char():
break
return a.get_visible_text(b)
# ex:ts=4:et:
| get_word | identifier_name |
utils.py | # -*- coding: utf-8 -*-
# gedit CodeCompletion plugin
# Copyright (C) 2011 Fabio Zendhi Nagao
#
# 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/>.
def get_word(piter):
a = piter.copy()
b = piter.copy()
while True:
if a.starts_line():
break
a.backward_char()
ch = a.get_char()
#if not (ch.isalnum() or ch in ['_', ':', '.', '-', '>']):
if not (ch.isalnum() or ch in "_:.->"):
a.forward_char()
break
word = a.get_visible_text(b)
return a, word
def get_document(piter):
a = piter.copy()
b = piter.copy()
while True:
|
while True:
if not b.forward_char():
break
return a.get_visible_text(b)
# ex:ts=4:et:
| if not a.backward_char():
break | conditional_block |
settings.py | """
Django settings for template project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mgu70)6s2vl#66ymf-iz=i8z05q==adv@6^*6^$8@p$bp8v04c'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'suit',
# django
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'django.contrib.humanize',
# custom
'core',
'users',
'questions',
'answers',
'reviews',
'reports',
'saas',
# third party
'allauth',
'allauth.account',
# 'allauth.socialaccount',
# 'allauth.socialaccount.providers.facebook',
# 'allauth.socialaccount.providers.twitter',
'crispy_forms',
'debug_toolbar',
'datatableview',
'compressor',
'sorl.thumbnail',
# 'cacheops',
'suit_redactor',
'mptt',
'autoslug',
'polymorphic',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
# third party
'ajaxerrors.middleware.ShowAJAXErrors',
)
ROOT_URLCONF = 'template.urls'
WSGI_APPLICATION = 'template.wsgi.application'
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Nairobi'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'OPTIONS': { | 'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
# custom
'django.template.context_processors.request',
"core.context_processors.site_processor",
"core.context_processors.debug_processor",
],
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.eggs.Loader',
]),
],
# 'loaders': [
# 'django.template.loaders.filesystem.Loader',
# 'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
# ],
'debug': False,
},
},
]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# other finders..
'compressor.finders.CompressorFinder',
)
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend"
)
# auth and allauth settings
LOGIN_REDIRECT_URL = '/dashboard'
SOCIALACCOUNT_QUERY_EMAIL = True
EMAIL_CONFIRMATION_DAYS = 14
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USER_DISPLAY = 'users.utils.get_user_display'
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'SCOPE': ['email', 'publish_stream'],
'METHOD': 'js_sdk' # instead of 'oauth2'
}
}
ACCOUNT_USERNAME_BLACKLIST = ['mosh', 'moshthepitt', 'kelvin', 'nicole', 'jay', "wambere"]
# crispy forms
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# Pagination
PAGINATION_DEFAULT_PAGINATION = 20
# COMPRESSOR
COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter',
'compressor.filters.cssmin.CSSMinFilter']
# CACHE OPS
CACHEOPS_REDIS = {
'host': 'localhost', # redis-server is on same machine
'port': 6379, # default redis port
'db': 2, # SELECT non-default redis database
# using separate redis db or redis instance
# is highly recommended
'socket_timeout': 3,
}
CACHEOPS_DEGRADE_ON_FAILURE = True
CACHEOPS = {
# automatically cache everything
'*.*': ('all', 60 * 10),
}
# Suit
SUIT_CONFIG = {
'ADMIN_NAME': 'JibuPro',
'SEARCH_URL': '',
}
# CELERY STUFF
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Africa/Nairobi'
QUESTION_LABEL_THUMBS_SIZE = "400"
try:
from local_settings import *
except ImportError, e:
pass | 'context_processors': [
# default
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug', | random_line_split |
castingsource0.rs | // Supprime tous les avertissements relatifs aux dépassements
// de capacité (e.g. une variable de type u8 ne peut pas
// contenir plus qu'une variable de type u16).
#![allow(overflowing_literals)]
fn main() {
| let decimal = 65.4321_f32;
// Erreur! La conversion implicite n'est pas supportée.
// let integer: u8 = decimal;
// FIXME ^ Décommentez/Commentez cette ligne pour voir
// le message d'erreur apparaître/disparaître.
// Conversion explicite.
let integer = decimal as u8;
let character = integer as char;
println!("Casting: {} -> {} -> {}", decimal, integer, character);
// Lorsque vous convertissez une valeur vers un type
// non-signé T, std::T::MAX + 1 est incrémenté ou soustrait jusqu'à
// ce que la valeur respecte la capacité du nouveau type.
// 1000 ne dépasse pas la capacité d'un entier non-signé codé sur 16 bits.
println!("1000 as a u16 is: {}", 1000 as u16);
// 1000 - 256 - 256 - 256 = 232
// En réalité, les 8 premiers bits les plus faibles (LSB) sont conservés et les
// bits les plus forts (MSB) restants sont tronqués.
println!("1000 as a u8 is : {}", 1000 as u8);
// -1 + 256 = 255
println!(" -1 as a u8 is : {}", (-1i8) as u8);
// Pour les nombres positifs, cette soustraction est équivalente à une
// division par 256.
println!("1000 mod 256 is : {}", 1000 % 256);
// Quand vous convertissez un type d'entiers signés, le résultat (bit à bit)
// est équivalent à celui de la conversion vers un type d'entiers non-signés.
// Si le bit de poids fort vaut 1, la valeur sera négative.
// Sauf si il n'y a pas de dépassements, évidemment.
println!(" 128 as a i16 is: {}", 128 as i16);
// 128 as u8 -> 128, complément à deux de 128 codé sur 8 bits:
println!(" 128 as a i8 is : {}", 128 as i8);
// On répète l'exemple ci-dessus.
// 1000 as u8 -> 232
println!("1000 as a i8 is : {}", 1000 as i8);
// et le complément à deux de 232 est -24.
println!(" 232 as a i8 is : {}", 232 as i8);
} | identifier_body | |
castingsource0.rs | // Supprime tous les avertissements relatifs aux dépassements
// de capacité (e.g. une variable de type u8 ne peut pas
// contenir plus qu'une variable de type u16).
#![allow(overflowing_literals)]
fn ma | {
let decimal = 65.4321_f32;
// Erreur! La conversion implicite n'est pas supportée.
// let integer: u8 = decimal;
// FIXME ^ Décommentez/Commentez cette ligne pour voir
// le message d'erreur apparaître/disparaître.
// Conversion explicite.
let integer = decimal as u8;
let character = integer as char;
println!("Casting: {} -> {} -> {}", decimal, integer, character);
// Lorsque vous convertissez une valeur vers un type
// non-signé T, std::T::MAX + 1 est incrémenté ou soustrait jusqu'à
// ce que la valeur respecte la capacité du nouveau type.
// 1000 ne dépasse pas la capacité d'un entier non-signé codé sur 16 bits.
println!("1000 as a u16 is: {}", 1000 as u16);
// 1000 - 256 - 256 - 256 = 232
// En réalité, les 8 premiers bits les plus faibles (LSB) sont conservés et les
// bits les plus forts (MSB) restants sont tronqués.
println!("1000 as a u8 is : {}", 1000 as u8);
// -1 + 256 = 255
println!(" -1 as a u8 is : {}", (-1i8) as u8);
// Pour les nombres positifs, cette soustraction est équivalente à une
// division par 256.
println!("1000 mod 256 is : {}", 1000 % 256);
// Quand vous convertissez un type d'entiers signés, le résultat (bit à bit)
// est équivalent à celui de la conversion vers un type d'entiers non-signés.
// Si le bit de poids fort vaut 1, la valeur sera négative.
// Sauf si il n'y a pas de dépassements, évidemment.
println!(" 128 as a i16 is: {}", 128 as i16);
// 128 as u8 -> 128, complément à deux de 128 codé sur 8 bits:
println!(" 128 as a i8 is : {}", 128 as i8);
// On répète l'exemple ci-dessus.
// 1000 as u8 -> 232
println!("1000 as a i8 is : {}", 1000 as i8);
// et le complément à deux de 232 est -24.
println!(" 232 as a i8 is : {}", 232 as i8);
} | in() | identifier_name |
castingsource0.rs | // Supprime tous les avertissements relatifs aux dépassements
// de capacité (e.g. une variable de type u8 ne peut pas
// contenir plus qu'une variable de type u16).
#![allow(overflowing_literals)]
fn main() {
let decimal = 65.4321_f32;
// Erreur! La conversion implicite n'est pas supportée.
// let integer: u8 = decimal;
// FIXME ^ Décommentez/Commentez cette ligne pour voir
// le message d'erreur apparaître/disparaître.
// Conversion explicite.
let integer = decimal as u8;
let character = integer as char;
println!("Casting: {} -> {} -> {}", decimal, integer, character);
// Lorsque vous convertissez une valeur vers un type
// non-signé T, std::T::MAX + 1 est incrémenté ou soustrait jusqu'à
// ce que la valeur respecte la capacité du nouveau type.
// 1000 ne dépasse pas la capacité d'un entier non-signé codé sur 16 bits.
println!("1000 as a u16 is: {}", 1000 as u16);
// 1000 - 256 - 256 - 256 = 232
// En réalité, les 8 premiers bits les plus faibles (LSB) sont conservés et les
// bits les plus forts (MSB) restants sont tronqués.
println!("1000 as a u8 is : {}", 1000 as u8);
// -1 + 256 = 255
println!(" -1 as a u8 is : {}", (-1i8) as u8);
// Pour les nombres positifs, cette soustraction est équivalente à une
// division par 256.
println!("1000 mod 256 is : {}", 1000 % 256);
// Quand vous convertissez un type d'entiers signés, le résultat (bit à bit)
// est équivalent à celui de la conversion vers un type d'entiers non-signés.
// Si le bit de poids fort vaut 1, la valeur sera négative.
// Sauf si il n'y a pas de dépassements, évidemment.
println!(" 128 as a i16 is: {}", 128 as i16);
// 128 as u8 -> 128, complément à deux de 128 codé sur 8 bits:
println!(" 128 as a i8 is : {}", 128 as i8);
// On répète l'exemple ci-dessus.
// 1000 as u8 -> 232
println!("1000 as a i8 is : {}", 1000 as i8);
// et le complément à deux de 232 est -24. |
} | println!(" 232 as a i8 is : {}", 232 as i8); | random_line_split |
Downloader.py | import pykka
from rx.subjects import *
from TorrentPython.DownloadManager import *
from TorrentPython.RoutingTable import *
class DownloaderActor(pykka.ThreadingActor):
def __init__(self, downloader):
super(DownloaderActor, self).__init__()
self.downloader = downloader
self.download_manager = DownloadManager(downloader)
def on_receive(self, message):
return message.get('func')(self)
def from_start(self):
pass
def from_stop(self):
pass
class Downloader(Subject):
def __init__(self, client_id, metainfo, path, routing_table=None):
|
def __del__(self):
self.destroy()
def destroy(self):
if self.actor.is_alive():
self.actor.stop()
def start(self):
self.actor.tell({'func': lambda x: x.from_start()})
def stop(self):
self.actor.tell({'func': lambda x: x.from_stop()})
| super(Downloader, self).__init__()
self.client_id = client_id
self.metainfo = metainfo
self.path = path
self.routing_table = routing_table or RoutingTable.INITIAL_ROUTING_TABLE
self.actor = DownloaderActor.start(self) | identifier_body |
Downloader.py | import pykka
from rx.subjects import *
from TorrentPython.DownloadManager import *
from TorrentPython.RoutingTable import *
| class DownloaderActor(pykka.ThreadingActor):
def __init__(self, downloader):
super(DownloaderActor, self).__init__()
self.downloader = downloader
self.download_manager = DownloadManager(downloader)
def on_receive(self, message):
return message.get('func')(self)
def from_start(self):
pass
def from_stop(self):
pass
class Downloader(Subject):
def __init__(self, client_id, metainfo, path, routing_table=None):
super(Downloader, self).__init__()
self.client_id = client_id
self.metainfo = metainfo
self.path = path
self.routing_table = routing_table or RoutingTable.INITIAL_ROUTING_TABLE
self.actor = DownloaderActor.start(self)
def __del__(self):
self.destroy()
def destroy(self):
if self.actor.is_alive():
self.actor.stop()
def start(self):
self.actor.tell({'func': lambda x: x.from_start()})
def stop(self):
self.actor.tell({'func': lambda x: x.from_stop()}) | random_line_split | |
Downloader.py | import pykka
from rx.subjects import *
from TorrentPython.DownloadManager import *
from TorrentPython.RoutingTable import *
class | (pykka.ThreadingActor):
def __init__(self, downloader):
super(DownloaderActor, self).__init__()
self.downloader = downloader
self.download_manager = DownloadManager(downloader)
def on_receive(self, message):
return message.get('func')(self)
def from_start(self):
pass
def from_stop(self):
pass
class Downloader(Subject):
def __init__(self, client_id, metainfo, path, routing_table=None):
super(Downloader, self).__init__()
self.client_id = client_id
self.metainfo = metainfo
self.path = path
self.routing_table = routing_table or RoutingTable.INITIAL_ROUTING_TABLE
self.actor = DownloaderActor.start(self)
def __del__(self):
self.destroy()
def destroy(self):
if self.actor.is_alive():
self.actor.stop()
def start(self):
self.actor.tell({'func': lambda x: x.from_start()})
def stop(self):
self.actor.tell({'func': lambda x: x.from_stop()})
| DownloaderActor | identifier_name |
Downloader.py | import pykka
from rx.subjects import *
from TorrentPython.DownloadManager import *
from TorrentPython.RoutingTable import *
class DownloaderActor(pykka.ThreadingActor):
def __init__(self, downloader):
super(DownloaderActor, self).__init__()
self.downloader = downloader
self.download_manager = DownloadManager(downloader)
def on_receive(self, message):
return message.get('func')(self)
def from_start(self):
pass
def from_stop(self):
pass
class Downloader(Subject):
def __init__(self, client_id, metainfo, path, routing_table=None):
super(Downloader, self).__init__()
self.client_id = client_id
self.metainfo = metainfo
self.path = path
self.routing_table = routing_table or RoutingTable.INITIAL_ROUTING_TABLE
self.actor = DownloaderActor.start(self)
def __del__(self):
self.destroy()
def destroy(self):
if self.actor.is_alive():
|
def start(self):
self.actor.tell({'func': lambda x: x.from_start()})
def stop(self):
self.actor.tell({'func': lambda x: x.from_stop()})
| self.actor.stop() | conditional_block |
Apartment.js | import React from 'react'
import ApartmentTable from './ApartmentListContainer'
import TextFieldForm from './ApartmentForm'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import {Tabs, Tab} from 'material-ui/Tabs'
import Paper from 'material-ui/Paper'
import AppBar from 'material-ui/AppBar'
import '../../css/apartment.css'
const styles = {
headline: {
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400
}
}
const style = {
height: 500,
width: 1000,
margin: 20,
textAlign: 'center',
display: 'inline-block'
}
const Apartment = () => (
<MuiThemeProvider>
<div className='apartment'>
<Tabs
initialSelectedIndex={0}
contentContainerClassName='5'
>
<Tab label='Apartment Form'>
<div style={{textAlign: 'center', margin: '25px'}}>
<Paper style={style} zDepth={1}>
<AppBar
title='Apartment Form'
showMenuIconButton={false}
/>
<TextFieldForm />
</Paper>
</div>
</Tab>
<Tab label='Apartment List'>
<div style={{textAlign: 'center', margin: '25px'}}>
<Paper style={style} zDepth={1}>
<AppBar
title='Apartment List'
showMenuIconButton={false}
/>
<ApartmentTable />
</Paper> | </div>
</MuiThemeProvider>
)
export default Apartment | </div>
</Tab>
</Tabs> | random_line_split |
complicajda.py | # 1. del: funkcije
#gender: female = 2, male = 0
def | (gender):
if gender == "male":
return 0
else: return 2
#age: 0-100 if age < 10 --> 0, 11 < age < 20 --> 5, 21 < age < 35 --> 2, 36 < age < 50 --> 4, 50+ --> 1
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age > 36 and age <= 50):
return 5
elif age > 20 and age <= 35:
return 2
elif age < 10:
return 0
else:
return 1
#status: 0 = single, 1 = relationship, 2 = in open relationship, 3 = it's complicated, 4 = I'm a pizza, 5 = depends who's asking
def calculate_score_for_status(status):
if status == "single":
return 0
elif status == "in a relationship":
return 1
elif status == "in an open relationship":
return 2
elif status == "it's complicated":
return 3
elif status == "I'm a pizza":
return 0
else:
return 5
# ignorance: 0 = Problem is my challenge, 1 = Who gives a fuck, 2 = I'm an angel
def calculate_score_for_ignorance(ignorance):
if ignorance == "Ignorance is bliss":
return 0
elif ignorance == "not at all":
return 2
elif ignorance == "I'm an angel":
return 4
# money_have: -10000+ = 6, (-10000)-(-5000) = 5, -5000-0 = 4, 0-500 = 3, 500-3000 = 2, 3000-10000 = 1, 10000+ = 0
def calculate_score_for_money_have(money_have):
if money_have <= (-10000.0):
return 8.0
elif money_have > (-10000.0) and money_have <= (-5000.0):
return 5.0
elif money_have > (-5000.0) and money_have <= 0.0:
return 4.0
elif money_have > 0.0 and money_have <= 500.0:
return 3.0
elif money_have > 500.0 and money_have <= 3000.0:
return 2.0
else:
return 0.0
# ---ZAKAJ MI NE PREPOZNA POZITIVNIH FLOATING NUMBERS IN NOBENE NEGATIVE (INTEGER ALI FLOATING NEGATIVNE) KOT STEVILKO?
# -->PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
# money_want: 0 = 0, 0-1000 = 1, 1000-5000 = 3, 5000-10000 = 4, 10000+ = 5
def caluculate_score_for_money_want(money_want):
if money_want == 0:
return 0
elif money_want > 0.0 and money_want <= 1000.0:
return 1
elif money_want > 1000.0 and money_want <= 5000.0:
return 3
elif money_want > 5000.0 and money_want <= 10000.0:
return 4
else:
return 5
#real friends: 0 = 5, 1-3 = 1, 4-6 = 2, 7-9 = 3, 10+ = 4
def calculate_score_for_rl_friends(rl_friends):
if rl_friends == 0:
return 5
elif rl_friends >= 1 and rl_friends <= 3:
return 1
elif rl_friends >= 4 and rl_friends <= 6:
return 2
elif rl_friends >= 7 and rl_friends <= 9:
return 3
else:
return 4
#children: 0 = 1, 1-2 = 2, 3 = 3, 4 = 4, 5+ = 5
def calculate_score_for_children(children):
if children == 0:
return 1
elif children == 1 and children == 2:
return 2
elif children == 3:
return 3
elif children == 4:
return 4
else:
return 5
# 2. del: sestevek funkcij
def calculate_score(gender, age, status, ignorance, money_have, money_want, rl_friends, children):
result = calculate_score_for_gender(gender)
result += calculate_score_for_age(age)
result += calculate_score_for_status(status)
result += calculate_score_for_ignorance(ignorance)
result += calculate_score_for_money_have(money_have)
result += caluculate_score_for_money_want(money_want)
result += calculate_score_for_rl_friends(rl_friends)
result += calculate_score_for_children(children)
return result
# 3. del: ------------- output za userja
#gender
print "Are you male or female?"
gender = raw_input(">> ")
#note to self: "while" pomeni da cekira na loop, "if" cekira enkratno
while (gender != "male") and (gender != "female"):
gender = raw_input("Check your gender again: ")
#age
print "How old are you?"
age = raw_input(">> ")
while not age.isdigit():
age = raw_input("Admit it, you're old. Now write your real age: ")
#status
print "What is your marital status?"
status = raw_input(">> ")
while (status != "single") and (status != "in a relationship") and (status != "in an open relationship") and (status != "it's complicated") and (status != "I'm a pizza"):
status = raw_input("Yeah, right... Think again: ")
#ignorance
print "How ignorant are you?"
ignorance = raw_input(">> ")
while (ignorance != "problem is my challenge") and (ignorance != "who gives a fuck") and (ignorance != "I'm an angel"):
ignorance = raw_input("You can't be that ignorant. Try again: ")
#money_have
print "How much money have you got?"
money_have = float(raw_input(">> "))
while not money_have:
money_have = float(raw_input("We aren't tax collectors, so be honest: "))
# PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
#money_want
print "In addition to the money you've got, how much money do you want to have?"
money_want = float(raw_input(">> "))
while money_want < 0: #---->zato, da je pozitivno stevilo!
money_want = float(raw_input("I didn't ask for apples and peaches. So, how much money do you want? "))
#rl_friends
print "How many real friends have you got?"
rl_friends = raw_input(">> ")
while not rl_friends.isdigit():
rl_friends = raw_input("Spock doesn't count. Think again - how many? ")
#children
print "How many children have you got?"
children = raw_input(">> ")
while not children.isdigit():
children = raw_input("No aliens, just humans, please: ")
# 4.del: sestevek
print "On a scale from 0 to 40, your life complication is : ", calculate_score(gender, int(age), status, ignorance, money_have, money_want, rl_friends, children)
| calculate_score_for_gender | identifier_name |
complicajda.py | # 1. del: funkcije
#gender: female = 2, male = 0
def calculate_score_for_gender(gender):
if gender == "male":
return 0
else: return 2
#age: 0-100 if age < 10 --> 0, 11 < age < 20 --> 5, 21 < age < 35 --> 2, 36 < age < 50 --> 4, 50+ --> 1
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age > 36 and age <= 50):
return 5
elif age > 20 and age <= 35:
return 2
elif age < 10:
return 0
else:
return 1
#status: 0 = single, 1 = relationship, 2 = in open relationship, 3 = it's complicated, 4 = I'm a pizza, 5 = depends who's asking
def calculate_score_for_status(status):
if status == "single":
return 0
elif status == "in a relationship":
return 1
elif status == "in an open relationship":
return 2
elif status == "it's complicated":
return 3
elif status == "I'm a pizza":
return 0
else:
return 5
# ignorance: 0 = Problem is my challenge, 1 = Who gives a fuck, 2 = I'm an angel
def calculate_score_for_ignorance(ignorance):
if ignorance == "Ignorance is bliss":
return 0
elif ignorance == "not at all":
return 2
elif ignorance == "I'm an angel":
return 4
# money_have: -10000+ = 6, (-10000)-(-5000) = 5, -5000-0 = 4, 0-500 = 3, 500-3000 = 2, 3000-10000 = 1, 10000+ = 0
def calculate_score_for_money_have(money_have):
if money_have <= (-10000.0):
return 8.0
elif money_have > (-10000.0) and money_have <= (-5000.0):
return 5.0
elif money_have > (-5000.0) and money_have <= 0.0:
|
elif money_have > 0.0 and money_have <= 500.0:
return 3.0
elif money_have > 500.0 and money_have <= 3000.0:
return 2.0
else:
return 0.0
# ---ZAKAJ MI NE PREPOZNA POZITIVNIH FLOATING NUMBERS IN NOBENE NEGATIVE (INTEGER ALI FLOATING NEGATIVNE) KOT STEVILKO?
# -->PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
# money_want: 0 = 0, 0-1000 = 1, 1000-5000 = 3, 5000-10000 = 4, 10000+ = 5
def caluculate_score_for_money_want(money_want):
if money_want == 0:
return 0
elif money_want > 0.0 and money_want <= 1000.0:
return 1
elif money_want > 1000.0 and money_want <= 5000.0:
return 3
elif money_want > 5000.0 and money_want <= 10000.0:
return 4
else:
return 5
#real friends: 0 = 5, 1-3 = 1, 4-6 = 2, 7-9 = 3, 10+ = 4
def calculate_score_for_rl_friends(rl_friends):
if rl_friends == 0:
return 5
elif rl_friends >= 1 and rl_friends <= 3:
return 1
elif rl_friends >= 4 and rl_friends <= 6:
return 2
elif rl_friends >= 7 and rl_friends <= 9:
return 3
else:
return 4
#children: 0 = 1, 1-2 = 2, 3 = 3, 4 = 4, 5+ = 5
def calculate_score_for_children(children):
if children == 0:
return 1
elif children == 1 and children == 2:
return 2
elif children == 3:
return 3
elif children == 4:
return 4
else:
return 5
# 2. del: sestevek funkcij
def calculate_score(gender, age, status, ignorance, money_have, money_want, rl_friends, children):
result = calculate_score_for_gender(gender)
result += calculate_score_for_age(age)
result += calculate_score_for_status(status)
result += calculate_score_for_ignorance(ignorance)
result += calculate_score_for_money_have(money_have)
result += caluculate_score_for_money_want(money_want)
result += calculate_score_for_rl_friends(rl_friends)
result += calculate_score_for_children(children)
return result
# 3. del: ------------- output za userja
#gender
print "Are you male or female?"
gender = raw_input(">> ")
#note to self: "while" pomeni da cekira na loop, "if" cekira enkratno
while (gender != "male") and (gender != "female"):
gender = raw_input("Check your gender again: ")
#age
print "How old are you?"
age = raw_input(">> ")
while not age.isdigit():
age = raw_input("Admit it, you're old. Now write your real age: ")
#status
print "What is your marital status?"
status = raw_input(">> ")
while (status != "single") and (status != "in a relationship") and (status != "in an open relationship") and (status != "it's complicated") and (status != "I'm a pizza"):
status = raw_input("Yeah, right... Think again: ")
#ignorance
print "How ignorant are you?"
ignorance = raw_input(">> ")
while (ignorance != "problem is my challenge") and (ignorance != "who gives a fuck") and (ignorance != "I'm an angel"):
ignorance = raw_input("You can't be that ignorant. Try again: ")
#money_have
print "How much money have you got?"
money_have = float(raw_input(">> "))
while not money_have:
money_have = float(raw_input("We aren't tax collectors, so be honest: "))
# PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
#money_want
print "In addition to the money you've got, how much money do you want to have?"
money_want = float(raw_input(">> "))
while money_want < 0: #---->zato, da je pozitivno stevilo!
money_want = float(raw_input("I didn't ask for apples and peaches. So, how much money do you want? "))
#rl_friends
print "How many real friends have you got?"
rl_friends = raw_input(">> ")
while not rl_friends.isdigit():
rl_friends = raw_input("Spock doesn't count. Think again - how many? ")
#children
print "How many children have you got?"
children = raw_input(">> ")
while not children.isdigit():
children = raw_input("No aliens, just humans, please: ")
# 4.del: sestevek
print "On a scale from 0 to 40, your life complication is : ", calculate_score(gender, int(age), status, ignorance, money_have, money_want, rl_friends, children)
| return 4.0 | conditional_block |
complicajda.py | # 1. del: funkcije
#gender: female = 2, male = 0
def calculate_score_for_gender(gender):
if gender == "male":
return 0
else: return 2
#age: 0-100 if age < 10 --> 0, 11 < age < 20 --> 5, 21 < age < 35 --> 2, 36 < age < 50 --> 4, 50+ --> 1
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age > 36 and age <= 50):
return 5
elif age > 20 and age <= 35:
return 2
elif age < 10:
return 0
else:
return 1
#status: 0 = single, 1 = relationship, 2 = in open relationship, 3 = it's complicated, 4 = I'm a pizza, 5 = depends who's asking
def calculate_score_for_status(status):
if status == "single":
return 0
elif status == "in a relationship":
return 1
elif status == "in an open relationship":
return 2
elif status == "it's complicated":
return 3
elif status == "I'm a pizza":
return 0
else:
return 5
# ignorance: 0 = Problem is my challenge, 1 = Who gives a fuck, 2 = I'm an angel
def calculate_score_for_ignorance(ignorance):
if ignorance == "Ignorance is bliss":
return 0
elif ignorance == "not at all":
return 2
elif ignorance == "I'm an angel":
return 4
# money_have: -10000+ = 6, (-10000)-(-5000) = 5, -5000-0 = 4, 0-500 = 3, 500-3000 = 2, 3000-10000 = 1, 10000+ = 0
def calculate_score_for_money_have(money_have):
if money_have <= (-10000.0):
return 8.0
elif money_have > (-10000.0) and money_have <= (-5000.0): |
elif money_have > 0.0 and money_have <= 500.0:
return 3.0
elif money_have > 500.0 and money_have <= 3000.0:
return 2.0
else:
return 0.0
# ---ZAKAJ MI NE PREPOZNA POZITIVNIH FLOATING NUMBERS IN NOBENE NEGATIVE (INTEGER ALI FLOATING NEGATIVNE) KOT STEVILKO?
# -->PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
# money_want: 0 = 0, 0-1000 = 1, 1000-5000 = 3, 5000-10000 = 4, 10000+ = 5
def caluculate_score_for_money_want(money_want):
if money_want == 0:
return 0
elif money_want > 0.0 and money_want <= 1000.0:
return 1
elif money_want > 1000.0 and money_want <= 5000.0:
return 3
elif money_want > 5000.0 and money_want <= 10000.0:
return 4
else:
return 5
#real friends: 0 = 5, 1-3 = 1, 4-6 = 2, 7-9 = 3, 10+ = 4
def calculate_score_for_rl_friends(rl_friends):
if rl_friends == 0:
return 5
elif rl_friends >= 1 and rl_friends <= 3:
return 1
elif rl_friends >= 4 and rl_friends <= 6:
return 2
elif rl_friends >= 7 and rl_friends <= 9:
return 3
else:
return 4
#children: 0 = 1, 1-2 = 2, 3 = 3, 4 = 4, 5+ = 5
def calculate_score_for_children(children):
if children == 0:
return 1
elif children == 1 and children == 2:
return 2
elif children == 3:
return 3
elif children == 4:
return 4
else:
return 5
# 2. del: sestevek funkcij
def calculate_score(gender, age, status, ignorance, money_have, money_want, rl_friends, children):
result = calculate_score_for_gender(gender)
result += calculate_score_for_age(age)
result += calculate_score_for_status(status)
result += calculate_score_for_ignorance(ignorance)
result += calculate_score_for_money_have(money_have)
result += caluculate_score_for_money_want(money_want)
result += calculate_score_for_rl_friends(rl_friends)
result += calculate_score_for_children(children)
return result
# 3. del: ------------- output za userja
#gender
print "Are you male or female?"
gender = raw_input(">> ")
#note to self: "while" pomeni da cekira na loop, "if" cekira enkratno
while (gender != "male") and (gender != "female"):
gender = raw_input("Check your gender again: ")
#age
print "How old are you?"
age = raw_input(">> ")
while not age.isdigit():
age = raw_input("Admit it, you're old. Now write your real age: ")
#status
print "What is your marital status?"
status = raw_input(">> ")
while (status != "single") and (status != "in a relationship") and (status != "in an open relationship") and (status != "it's complicated") and (status != "I'm a pizza"):
status = raw_input("Yeah, right... Think again: ")
#ignorance
print "How ignorant are you?"
ignorance = raw_input(">> ")
while (ignorance != "problem is my challenge") and (ignorance != "who gives a fuck") and (ignorance != "I'm an angel"):
ignorance = raw_input("You can't be that ignorant. Try again: ")
#money_have
print "How much money have you got?"
money_have = float(raw_input(">> "))
while not money_have:
money_have = float(raw_input("We aren't tax collectors, so be honest: "))
# PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
#money_want
print "In addition to the money you've got, how much money do you want to have?"
money_want = float(raw_input(">> "))
while money_want < 0: #---->zato, da je pozitivno stevilo!
money_want = float(raw_input("I didn't ask for apples and peaches. So, how much money do you want? "))
#rl_friends
print "How many real friends have you got?"
rl_friends = raw_input(">> ")
while not rl_friends.isdigit():
rl_friends = raw_input("Spock doesn't count. Think again - how many? ")
#children
print "How many children have you got?"
children = raw_input(">> ")
while not children.isdigit():
children = raw_input("No aliens, just humans, please: ")
# 4.del: sestevek
print "On a scale from 0 to 40, your life complication is : ", calculate_score(gender, int(age), status, ignorance, money_have, money_want, rl_friends, children) | return 5.0
elif money_have > (-5000.0) and money_have <= 0.0:
return 4.0 | random_line_split |
complicajda.py | # 1. del: funkcije
#gender: female = 2, male = 0
def calculate_score_for_gender(gender):
if gender == "male":
return 0
else: return 2
#age: 0-100 if age < 10 --> 0, 11 < age < 20 --> 5, 21 < age < 35 --> 2, 36 < age < 50 --> 4, 50+ --> 1
def calculate_score_for_age(age):
if (age > 11 and age <= 20) or (age > 36 and age <= 50):
return 5
elif age > 20 and age <= 35:
return 2
elif age < 10:
return 0
else:
return 1
#status: 0 = single, 1 = relationship, 2 = in open relationship, 3 = it's complicated, 4 = I'm a pizza, 5 = depends who's asking
def calculate_score_for_status(status):
if status == "single":
return 0
elif status == "in a relationship":
return 1
elif status == "in an open relationship":
return 2
elif status == "it's complicated":
return 3
elif status == "I'm a pizza":
return 0
else:
return 5
# ignorance: 0 = Problem is my challenge, 1 = Who gives a fuck, 2 = I'm an angel
def calculate_score_for_ignorance(ignorance):
if ignorance == "Ignorance is bliss":
return 0
elif ignorance == "not at all":
return 2
elif ignorance == "I'm an angel":
return 4
# money_have: -10000+ = 6, (-10000)-(-5000) = 5, -5000-0 = 4, 0-500 = 3, 500-3000 = 2, 3000-10000 = 1, 10000+ = 0
def calculate_score_for_money_have(money_have):
if money_have <= (-10000.0):
return 8.0
elif money_have > (-10000.0) and money_have <= (-5000.0):
return 5.0
elif money_have > (-5000.0) and money_have <= 0.0:
return 4.0
elif money_have > 0.0 and money_have <= 500.0:
return 3.0
elif money_have > 500.0 and money_have <= 3000.0:
return 2.0
else:
return 0.0
# ---ZAKAJ MI NE PREPOZNA POZITIVNIH FLOATING NUMBERS IN NOBENE NEGATIVE (INTEGER ALI FLOATING NEGATIVNE) KOT STEVILKO?
# -->PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
# money_want: 0 = 0, 0-1000 = 1, 1000-5000 = 3, 5000-10000 = 4, 10000+ = 5
def caluculate_score_for_money_want(money_want):
if money_want == 0:
return 0
elif money_want > 0.0 and money_want <= 1000.0:
return 1
elif money_want > 1000.0 and money_want <= 5000.0:
return 3
elif money_want > 5000.0 and money_want <= 10000.0:
return 4
else:
return 5
#real friends: 0 = 5, 1-3 = 1, 4-6 = 2, 7-9 = 3, 10+ = 4
def calculate_score_for_rl_friends(rl_friends):
if rl_friends == 0:
return 5
elif rl_friends >= 1 and rl_friends <= 3:
return 1
elif rl_friends >= 4 and rl_friends <= 6:
return 2
elif rl_friends >= 7 and rl_friends <= 9:
return 3
else:
return 4
#children: 0 = 1, 1-2 = 2, 3 = 3, 4 = 4, 5+ = 5
def calculate_score_for_children(children):
|
# 2. del: sestevek funkcij
def calculate_score(gender, age, status, ignorance, money_have, money_want, rl_friends, children):
result = calculate_score_for_gender(gender)
result += calculate_score_for_age(age)
result += calculate_score_for_status(status)
result += calculate_score_for_ignorance(ignorance)
result += calculate_score_for_money_have(money_have)
result += caluculate_score_for_money_want(money_want)
result += calculate_score_for_rl_friends(rl_friends)
result += calculate_score_for_children(children)
return result
# 3. del: ------------- output za userja
#gender
print "Are you male or female?"
gender = raw_input(">> ")
#note to self: "while" pomeni da cekira na loop, "if" cekira enkratno
while (gender != "male") and (gender != "female"):
gender = raw_input("Check your gender again: ")
#age
print "How old are you?"
age = raw_input(">> ")
while not age.isdigit():
age = raw_input("Admit it, you're old. Now write your real age: ")
#status
print "What is your marital status?"
status = raw_input(">> ")
while (status != "single") and (status != "in a relationship") and (status != "in an open relationship") and (status != "it's complicated") and (status != "I'm a pizza"):
status = raw_input("Yeah, right... Think again: ")
#ignorance
print "How ignorant are you?"
ignorance = raw_input(">> ")
while (ignorance != "problem is my challenge") and (ignorance != "who gives a fuck") and (ignorance != "I'm an angel"):
ignorance = raw_input("You can't be that ignorant. Try again: ")
#money_have
print "How much money have you got?"
money_have = float(raw_input(">> "))
while not money_have:
money_have = float(raw_input("We aren't tax collectors, so be honest: "))
# PRED RAW INPUT MORAS DAT FLOAT, CE NI CELA STEVILKA IN ODSTRANI .ISDIGIT, KER .ISDIGIT JE LE ZA CELE STEVILKE!
#money_want
print "In addition to the money you've got, how much money do you want to have?"
money_want = float(raw_input(">> "))
while money_want < 0: #---->zato, da je pozitivno stevilo!
money_want = float(raw_input("I didn't ask for apples and peaches. So, how much money do you want? "))
#rl_friends
print "How many real friends have you got?"
rl_friends = raw_input(">> ")
while not rl_friends.isdigit():
rl_friends = raw_input("Spock doesn't count. Think again - how many? ")
#children
print "How many children have you got?"
children = raw_input(">> ")
while not children.isdigit():
children = raw_input("No aliens, just humans, please: ")
# 4.del: sestevek
print "On a scale from 0 to 40, your life complication is : ", calculate_score(gender, int(age), status, ignorance, money_have, money_want, rl_friends, children)
| if children == 0:
return 1
elif children == 1 and children == 2:
return 2
elif children == 3:
return 3
elif children == 4:
return 4
else:
return 5 | identifier_body |
projects.js | var mongoose = require('mongoose');
var rooms = require('./rooms');
mongoose.connect('mongodb://localhost:27017/rpgd');
var RoomSchema = require('mongoose').model('Room').schema;
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// Setup Database scheme
var ProjectSchema = new Schema({
name: String,
subtitle: String,
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
contributors: [UserSchema],
summary: String,
description: String,
comments: [CommentSchema],
created: {
type: Date,
default: Date.now()
},
private: { | default: false
},
meta: {
votes: Number,
favs: Number
},
rooms: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Room'
}]
});
var User = mongoose.model('User', UserSchema);
var Project = mongoose.model('Project', ProjectSchema);
var handleError = function (err) {
console.log('Error', err);
}
exports.findById = function (req, res) {
Project.findOne({
'_id': req.params.id
}, function (err, project) {
if (err) return handleError(err);
res.send(project);
})
.populate('createdBy')
.populate('rooms')
};
exports.findAll = function (req, res) {
Project.find({}, function (err, projects) {
if (err) handleError(err);
res.send(projects);
});
};
exports.updateRoom = function (req, res) {
/*Project.findByIdAndUpdate(
info._id,
{$push: {"rooms": }}
)
Contact.findByIdAndUpdate(
info._id,
{$push: {"messages": {title: title, msg: msg}}},
{safe: true, upsert: true, new : true},
function(err, model) {
console.log(err);
}
);
*/
}
exports.addRoom = function (req, res) {
// find by document id and update
Project.findByIdAndUpdate(
req.params.projectId, {
$push: {
rooms: req.body
}
}, {
safe: true,
upsert: true
},
function (err, model) {
console.log(err);
}
);
res.send('Done')
}
exports.addProject = function (req, res) {
console.log('Request: ' + req);
console.log('Request body: ' + req.body);
var pro = new Project(req.body);
console.log('Crating new project ' + pro);
pro.save(function (err, result) {
if (err) return handleError(err);
res.send('Project created');
})
}
exports.updateProject = function (req, res) {}
exports.deleteProject = function (req, res) {} | type: Boolean, | random_line_split |
fb_oauth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Facebook OAuth interface."""
# System imports
import json
import logging
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
import oauth2 as oauth
from django.conf import settings
# Project imports
from .base_auth import Base3rdPartyAuth
logger = logging.getLogger(__name__)
|
consumer = oauth.Consumer(key=settings.FACEBOOK_APP_ID, secret=settings.FACEBOOK_APP_SECRET)
class FacebookOAuth(Base3rdPartyAuth):
PROVIDER = 'facebook'
BACKEND = 'draalcore.auth.backend.FacebookOAuthBackend'
def get_authorize_url(self, request):
"""Request and prepare URL for login using Facebook account."""
base_url = '{}?client_id={}&redirect_uri={}&scope={}'
return base_url.format(FACEBOOK_REQUEST_TOKEN_URL, settings.FACEBOOK_APP_ID,
quote_plus(self.get_callback_url()), 'email')
def set_user(self, response):
return self.get_user({
'username': 'fb-{}'.format(response['id']),
'email': response['email'],
'first_name': response['first_name'],
'last_name': response['last_name'],
})
def authorize(self, request):
base_url = '{}?client_id={}&redirect_uri={}&client_secret={}&code={}'
request_url = base_url.format(FACEBOOK_ACCESS_TOKEN_URL, settings.FACEBOOK_APP_ID,
self.get_callback_url(), settings.FACEBOOK_APP_SECRET,
request.GET.get('code'))
# Get the access token from Facebook
client = oauth.Client(consumer)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
# Get profile info from Facebook
base_url = '{}?access_token={}&fields=id,first_name,last_name,email'
access_token = json.loads(content)['access_token']
request_url = base_url.format(FACEBOOK_CHECK_AUTH, access_token)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
user_data = json.loads(content)
# Authenticate user
logger.debug(user_data)
user = self.set_user(user_data)
return self.authenticate(request, user.username)
self.login_failure() |
FACEBOOK_REQUEST_TOKEN_URL = 'https://www.facebook.com/dialog/oauth'
FACEBOOK_ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
FACEBOOK_CHECK_AUTH = 'https://graph.facebook.com/me' | random_line_split |
fb_oauth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Facebook OAuth interface."""
# System imports
import json
import logging
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
import oauth2 as oauth
from django.conf import settings
# Project imports
from .base_auth import Base3rdPartyAuth
logger = logging.getLogger(__name__)
FACEBOOK_REQUEST_TOKEN_URL = 'https://www.facebook.com/dialog/oauth'
FACEBOOK_ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
FACEBOOK_CHECK_AUTH = 'https://graph.facebook.com/me'
consumer = oauth.Consumer(key=settings.FACEBOOK_APP_ID, secret=settings.FACEBOOK_APP_SECRET)
class FacebookOAuth(Base3rdPartyAuth):
PROVIDER = 'facebook'
BACKEND = 'draalcore.auth.backend.FacebookOAuthBackend'
def get_authorize_url(self, request):
"""Request and prepare URL for login using Facebook account."""
base_url = '{}?client_id={}&redirect_uri={}&scope={}'
return base_url.format(FACEBOOK_REQUEST_TOKEN_URL, settings.FACEBOOK_APP_ID,
quote_plus(self.get_callback_url()), 'email')
def | (self, response):
return self.get_user({
'username': 'fb-{}'.format(response['id']),
'email': response['email'],
'first_name': response['first_name'],
'last_name': response['last_name'],
})
def authorize(self, request):
base_url = '{}?client_id={}&redirect_uri={}&client_secret={}&code={}'
request_url = base_url.format(FACEBOOK_ACCESS_TOKEN_URL, settings.FACEBOOK_APP_ID,
self.get_callback_url(), settings.FACEBOOK_APP_SECRET,
request.GET.get('code'))
# Get the access token from Facebook
client = oauth.Client(consumer)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
# Get profile info from Facebook
base_url = '{}?access_token={}&fields=id,first_name,last_name,email'
access_token = json.loads(content)['access_token']
request_url = base_url.format(FACEBOOK_CHECK_AUTH, access_token)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
user_data = json.loads(content)
# Authenticate user
logger.debug(user_data)
user = self.set_user(user_data)
return self.authenticate(request, user.username)
self.login_failure()
| set_user | identifier_name |
fb_oauth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Facebook OAuth interface."""
# System imports
import json
import logging
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
import oauth2 as oauth
from django.conf import settings
# Project imports
from .base_auth import Base3rdPartyAuth
logger = logging.getLogger(__name__)
FACEBOOK_REQUEST_TOKEN_URL = 'https://www.facebook.com/dialog/oauth'
FACEBOOK_ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
FACEBOOK_CHECK_AUTH = 'https://graph.facebook.com/me'
consumer = oauth.Consumer(key=settings.FACEBOOK_APP_ID, secret=settings.FACEBOOK_APP_SECRET)
class FacebookOAuth(Base3rdPartyAuth):
PROVIDER = 'facebook'
BACKEND = 'draalcore.auth.backend.FacebookOAuthBackend'
def get_authorize_url(self, request):
"""Request and prepare URL for login using Facebook account."""
base_url = '{}?client_id={}&redirect_uri={}&scope={}'
return base_url.format(FACEBOOK_REQUEST_TOKEN_URL, settings.FACEBOOK_APP_ID,
quote_plus(self.get_callback_url()), 'email')
def set_user(self, response):
return self.get_user({
'username': 'fb-{}'.format(response['id']),
'email': response['email'],
'first_name': response['first_name'],
'last_name': response['last_name'],
})
def authorize(self, request):
base_url = '{}?client_id={}&redirect_uri={}&client_secret={}&code={}'
request_url = base_url.format(FACEBOOK_ACCESS_TOKEN_URL, settings.FACEBOOK_APP_ID,
self.get_callback_url(), settings.FACEBOOK_APP_SECRET,
request.GET.get('code'))
# Get the access token from Facebook
client = oauth.Client(consumer)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
# Get profile info from Facebook
base_url = '{}?access_token={}&fields=id,first_name,last_name,email'
access_token = json.loads(content)['access_token']
request_url = base_url.format(FACEBOOK_CHECK_AUTH, access_token)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
|
self.login_failure()
| user_data = json.loads(content)
# Authenticate user
logger.debug(user_data)
user = self.set_user(user_data)
return self.authenticate(request, user.username) | conditional_block |
fb_oauth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Facebook OAuth interface."""
# System imports
import json
import logging
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
import oauth2 as oauth
from django.conf import settings
# Project imports
from .base_auth import Base3rdPartyAuth
logger = logging.getLogger(__name__)
FACEBOOK_REQUEST_TOKEN_URL = 'https://www.facebook.com/dialog/oauth'
FACEBOOK_ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
FACEBOOK_CHECK_AUTH = 'https://graph.facebook.com/me'
consumer = oauth.Consumer(key=settings.FACEBOOK_APP_ID, secret=settings.FACEBOOK_APP_SECRET)
class FacebookOAuth(Base3rdPartyAuth):
PROVIDER = 'facebook'
BACKEND = 'draalcore.auth.backend.FacebookOAuthBackend'
def get_authorize_url(self, request):
"""Request and prepare URL for login using Facebook account."""
base_url = '{}?client_id={}&redirect_uri={}&scope={}'
return base_url.format(FACEBOOK_REQUEST_TOKEN_URL, settings.FACEBOOK_APP_ID,
quote_plus(self.get_callback_url()), 'email')
def set_user(self, response):
|
def authorize(self, request):
base_url = '{}?client_id={}&redirect_uri={}&client_secret={}&code={}'
request_url = base_url.format(FACEBOOK_ACCESS_TOKEN_URL, settings.FACEBOOK_APP_ID,
self.get_callback_url(), settings.FACEBOOK_APP_SECRET,
request.GET.get('code'))
# Get the access token from Facebook
client = oauth.Client(consumer)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
# Get profile info from Facebook
base_url = '{}?access_token={}&fields=id,first_name,last_name,email'
access_token = json.loads(content)['access_token']
request_url = base_url.format(FACEBOOK_CHECK_AUTH, access_token)
response, content = client.request(request_url, 'GET')
if response['status'] == '200':
user_data = json.loads(content)
# Authenticate user
logger.debug(user_data)
user = self.set_user(user_data)
return self.authenticate(request, user.username)
self.login_failure()
| return self.get_user({
'username': 'fb-{}'.format(response['id']),
'email': response['email'],
'first_name': response['first_name'],
'last_name': response['last_name'],
}) | identifier_body |
htmlvideoelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLVideoElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlmediaelement::HTMLMediaElement;
use dom::node::Node;
use util::str::DOMString;
#[dom_struct]
pub struct | {
htmlmediaelement: HTMLMediaElement
}
impl HTMLVideoElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLVideoElement {
HTMLVideoElement {
htmlmediaelement:
HTMLMediaElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLVideoElement> {
let element = HTMLVideoElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLVideoElementBinding::Wrap)
}
}
| HTMLVideoElement | identifier_name |
htmlvideoelement.rs |
use dom::bindings::codegen::Bindings::HTMLVideoElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlmediaelement::HTMLMediaElement;
use dom::node::Node;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLVideoElement {
htmlmediaelement: HTMLMediaElement
}
impl HTMLVideoElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLVideoElement {
HTMLVideoElement {
htmlmediaelement:
HTMLMediaElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLVideoElement> {
let element = HTMLVideoElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLVideoElementBinding::Wrap)
}
} | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split | |
cmac.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides an implementation of MAC using AES-CMAC.
use tink_core::{utils::wrap_err, Prf, TinkError};
const MIN_CMAC_KEY_SIZE_IN_BYTES: usize = 16;
const RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES: usize = 32;
const MIN_TAG_LENGTH_IN_BYTES: usize = 10;
const MAX_TAG_LENGTH_IN_BYTES: usize = 16;
/// `AesCmac` represents an AES-CMAC struct that implements the [`tink_core::Mac`] interface.
#[derive(Clone)]
pub struct AesCmac {
prf: tink_prf::subtle::AesCmacPrf,
tag_size: usize,
}
impl AesCmac {
/// Create a new [`AesCmac`] object that implements the [`tink_core::Mac`] interface.
pub fn new(key: &[u8], tag_size: usize) -> Result<AesCmac, TinkError> {
if key.len() < MIN_CMAC_KEY_SIZE_IN_BYTES {
return Err("AesCmac: Only 256 bit keys are allowed".into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is shorter than minimum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is longer than maximum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
let prf = tink_prf::subtle::AesCmacPrf::new(key)
.map_err(|e| wrap_err("AesCmac: could not create AES-CMAC prf", e))?;
Ok(AesCmac { prf, tag_size })
}
}
impl tink_core::Mac for AesCmac {
fn compute_mac(&self, data: &[u8]) -> Result<Vec<u8>, TinkError> {
self.prf.compute_prf(data, self.tag_size)
}
}
/// Validate the parameters for an AES-CMAC against the recommended parameters.
pub fn validate_cmac_params(key_size: usize, tag_size: usize) -> Result<(), TinkError> {
if key_size != RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES {
return Err(format!(
"Only {} sized keys are allowed with Tink's AES-CMAC",
RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES
)
.into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES |
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err("Tag size too long".into());
}
Ok(())
}
| {
return Err("Tag size too short".into());
} | conditional_block |
cmac.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides an implementation of MAC using AES-CMAC.
use tink_core::{utils::wrap_err, Prf, TinkError};
const MIN_CMAC_KEY_SIZE_IN_BYTES: usize = 16;
const RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES: usize = 32;
const MIN_TAG_LENGTH_IN_BYTES: usize = 10;
const MAX_TAG_LENGTH_IN_BYTES: usize = 16;
/// `AesCmac` represents an AES-CMAC struct that implements the [`tink_core::Mac`] interface.
#[derive(Clone)]
pub struct AesCmac {
prf: tink_prf::subtle::AesCmacPrf,
tag_size: usize,
}
impl AesCmac {
/// Create a new [`AesCmac`] object that implements the [`tink_core::Mac`] interface.
pub fn new(key: &[u8], tag_size: usize) -> Result<AesCmac, TinkError> {
if key.len() < MIN_CMAC_KEY_SIZE_IN_BYTES {
return Err("AesCmac: Only 256 bit keys are allowed".into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is shorter than minimum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is longer than maximum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
let prf = tink_prf::subtle::AesCmacPrf::new(key)
.map_err(|e| wrap_err("AesCmac: could not create AES-CMAC prf", e))?;
Ok(AesCmac { prf, tag_size })
}
}
impl tink_core::Mac for AesCmac {
fn compute_mac(&self, data: &[u8]) -> Result<Vec<u8>, TinkError> {
self.prf.compute_prf(data, self.tag_size)
}
}
/// Validate the parameters for an AES-CMAC against the recommended parameters.
pub fn validate_cmac_params(key_size: usize, tag_size: usize) -> Result<(), TinkError> {
if key_size != RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES {
return Err(format!(
"Only {} sized keys are allowed with Tink's AES-CMAC",
RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES
)
.into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES { | return Err("Tag size too short".into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err("Tag size too long".into());
}
Ok(())
} | random_line_split | |
cmac.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides an implementation of MAC using AES-CMAC.
use tink_core::{utils::wrap_err, Prf, TinkError};
const MIN_CMAC_KEY_SIZE_IN_BYTES: usize = 16;
const RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES: usize = 32;
const MIN_TAG_LENGTH_IN_BYTES: usize = 10;
const MAX_TAG_LENGTH_IN_BYTES: usize = 16;
/// `AesCmac` represents an AES-CMAC struct that implements the [`tink_core::Mac`] interface.
#[derive(Clone)]
pub struct AesCmac {
prf: tink_prf::subtle::AesCmacPrf,
tag_size: usize,
}
impl AesCmac {
/// Create a new [`AesCmac`] object that implements the [`tink_core::Mac`] interface.
pub fn new(key: &[u8], tag_size: usize) -> Result<AesCmac, TinkError> {
if key.len() < MIN_CMAC_KEY_SIZE_IN_BYTES {
return Err("AesCmac: Only 256 bit keys are allowed".into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is shorter than minimum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is longer than maximum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
let prf = tink_prf::subtle::AesCmacPrf::new(key)
.map_err(|e| wrap_err("AesCmac: could not create AES-CMAC prf", e))?;
Ok(AesCmac { prf, tag_size })
}
}
impl tink_core::Mac for AesCmac {
fn | (&self, data: &[u8]) -> Result<Vec<u8>, TinkError> {
self.prf.compute_prf(data, self.tag_size)
}
}
/// Validate the parameters for an AES-CMAC against the recommended parameters.
pub fn validate_cmac_params(key_size: usize, tag_size: usize) -> Result<(), TinkError> {
if key_size != RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES {
return Err(format!(
"Only {} sized keys are allowed with Tink's AES-CMAC",
RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES
)
.into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES {
return Err("Tag size too short".into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err("Tag size too long".into());
}
Ok(())
}
| compute_mac | identifier_name |
cmac.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provides an implementation of MAC using AES-CMAC.
use tink_core::{utils::wrap_err, Prf, TinkError};
const MIN_CMAC_KEY_SIZE_IN_BYTES: usize = 16;
const RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES: usize = 32;
const MIN_TAG_LENGTH_IN_BYTES: usize = 10;
const MAX_TAG_LENGTH_IN_BYTES: usize = 16;
/// `AesCmac` represents an AES-CMAC struct that implements the [`tink_core::Mac`] interface.
#[derive(Clone)]
pub struct AesCmac {
prf: tink_prf::subtle::AesCmacPrf,
tag_size: usize,
}
impl AesCmac {
/// Create a new [`AesCmac`] object that implements the [`tink_core::Mac`] interface.
pub fn new(key: &[u8], tag_size: usize) -> Result<AesCmac, TinkError> {
if key.len() < MIN_CMAC_KEY_SIZE_IN_BYTES {
return Err("AesCmac: Only 256 bit keys are allowed".into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is shorter than minimum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err(format!(
"AesCmac: tag length {} is longer than maximum tag length {}",
tag_size, MIN_TAG_LENGTH_IN_BYTES
)
.into());
}
let prf = tink_prf::subtle::AesCmacPrf::new(key)
.map_err(|e| wrap_err("AesCmac: could not create AES-CMAC prf", e))?;
Ok(AesCmac { prf, tag_size })
}
}
impl tink_core::Mac for AesCmac {
fn compute_mac(&self, data: &[u8]) -> Result<Vec<u8>, TinkError> {
self.prf.compute_prf(data, self.tag_size)
}
}
/// Validate the parameters for an AES-CMAC against the recommended parameters.
pub fn validate_cmac_params(key_size: usize, tag_size: usize) -> Result<(), TinkError> | {
if key_size != RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES {
return Err(format!(
"Only {} sized keys are allowed with Tink's AES-CMAC",
RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES
)
.into());
}
if tag_size < MIN_TAG_LENGTH_IN_BYTES {
return Err("Tag size too short".into());
}
if tag_size > MAX_TAG_LENGTH_IN_BYTES {
return Err("Tag size too long".into());
}
Ok(())
} | identifier_body | |
011.py | def format():
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
text_arr = text.split('\n')
global arr
arr = [[] for _ in range(21)]
for i in range(21):
arr[i].append(text_arr[i])
#Remove the empty string in the array
arr.pop(20)
for j in range(20):
arr[j][0] = arr[j][0].split(' ')
#List created - arr[i][0][j]
#Convert all numbers to integers
for a in range(20):
for b in range(20):
arr[a][0][b] = int(arr[a][0][b])
def main():
format()
global arr
greatest = 0
for i in range(20):
for j in range(16):
# horizontal products
prod = arr[i][0][j]*arr[i][0][j+1]*arr[i][0][j+2]*arr[i][0][j+3]
if prod > greatest:
greatest = prod
# vertical products
prod = arr[j][0][i]*arr[j+1][0][i]*arr[j+2][0][i]*arr[j+3][0][i]
if prod > greatest:
greatest = prod
# diagonal products
for i in range(16):
for j in range(16):
prod = arr[i][0][j]*arr[i+1][0][j+1]*arr[i+2][0][j+2]*arr[i+3][0][j+3]
if prod > greatest:
greatest = prod
for i in range(3,20):
for j in range(16): | prod = arr[i][0][j]*arr[i-1][0][j+1]*arr[i-2][0][j+2]*arr[i-3][0][j+3]
if prod > greatest:
greatest = prod
print greatest
main() | random_line_split | |
011.py | def format():
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
text_arr = text.split('\n')
global arr
arr = [[] for _ in range(21)]
for i in range(21):
arr[i].append(text_arr[i])
#Remove the empty string in the array
arr.pop(20)
for j in range(20):
arr[j][0] = arr[j][0].split(' ')
#List created - arr[i][0][j]
#Convert all numbers to integers
for a in range(20):
for b in range(20):
arr[a][0][b] = int(arr[a][0][b])
def main():
format()
global arr
greatest = 0
for i in range(20):
for j in range(16):
# horizontal products
prod = arr[i][0][j]*arr[i][0][j+1]*arr[i][0][j+2]*arr[i][0][j+3]
if prod > greatest:
greatest = prod
# vertical products
prod = arr[j][0][i]*arr[j+1][0][i]*arr[j+2][0][i]*arr[j+3][0][i]
if prod > greatest:
greatest = prod
# diagonal products
for i in range(16):
for j in range(16):
prod = arr[i][0][j]*arr[i+1][0][j+1]*arr[i+2][0][j+2]*arr[i+3][0][j+3]
if prod > greatest:
greatest = prod
for i in range(3,20):
for j in range(16):
prod = arr[i][0][j]*arr[i-1][0][j+1]*arr[i-2][0][j+2]*arr[i-3][0][j+3]
if prod > greatest:
|
print greatest
main()
| greatest = prod | conditional_block |
011.py | def format():
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
text_arr = text.split('\n')
global arr
arr = [[] for _ in range(21)]
for i in range(21):
arr[i].append(text_arr[i])
#Remove the empty string in the array
arr.pop(20)
for j in range(20):
arr[j][0] = arr[j][0].split(' ')
#List created - arr[i][0][j]
#Convert all numbers to integers
for a in range(20):
for b in range(20):
arr[a][0][b] = int(arr[a][0][b])
def main():
|
main()
| format()
global arr
greatest = 0
for i in range(20):
for j in range(16):
# horizontal products
prod = arr[i][0][j]*arr[i][0][j+1]*arr[i][0][j+2]*arr[i][0][j+3]
if prod > greatest:
greatest = prod
# vertical products
prod = arr[j][0][i]*arr[j+1][0][i]*arr[j+2][0][i]*arr[j+3][0][i]
if prod > greatest:
greatest = prod
# diagonal products
for i in range(16):
for j in range(16):
prod = arr[i][0][j]*arr[i+1][0][j+1]*arr[i+2][0][j+2]*arr[i+3][0][j+3]
if prod > greatest:
greatest = prod
for i in range(3,20):
for j in range(16):
prod = arr[i][0][j]*arr[i-1][0][j+1]*arr[i-2][0][j+2]*arr[i-3][0][j+3]
if prod > greatest:
greatest = prod
print greatest | identifier_body |
011.py | def format():
text = ""
stopword = ""
while True:
line = raw_input()
if line.strip() == stopword:
break
text += "%s\n" % line
text_arr = text.split('\n')
global arr
arr = [[] for _ in range(21)]
for i in range(21):
arr[i].append(text_arr[i])
#Remove the empty string in the array
arr.pop(20)
for j in range(20):
arr[j][0] = arr[j][0].split(' ')
#List created - arr[i][0][j]
#Convert all numbers to integers
for a in range(20):
for b in range(20):
arr[a][0][b] = int(arr[a][0][b])
def | ():
format()
global arr
greatest = 0
for i in range(20):
for j in range(16):
# horizontal products
prod = arr[i][0][j]*arr[i][0][j+1]*arr[i][0][j+2]*arr[i][0][j+3]
if prod > greatest:
greatest = prod
# vertical products
prod = arr[j][0][i]*arr[j+1][0][i]*arr[j+2][0][i]*arr[j+3][0][i]
if prod > greatest:
greatest = prod
# diagonal products
for i in range(16):
for j in range(16):
prod = arr[i][0][j]*arr[i+1][0][j+1]*arr[i+2][0][j+2]*arr[i+3][0][j+3]
if prod > greatest:
greatest = prod
for i in range(3,20):
for j in range(16):
prod = arr[i][0][j]*arr[i-1][0][j+1]*arr[i-2][0][j+2]*arr[i-3][0][j+3]
if prod > greatest:
greatest = prod
print greatest
main()
| main | identifier_name |
home_page.js | // DOM Manipulation Challenge
// I worked on this challenge with: Austin Dorff.
// Add your JavaScript calls to this page:
// Release 0:
// Set up
// Release 1:
var div_r_1 = document.getElementById("release-0");
div_r_1.className = "done";
// Release 2:
var div_r_2 = document.getElementById('release-1');
div_r_2.style.display = "none";
// Release 3:
var div_r_3 = document.getElementsByTagName('h1')[0];
div_r_3.innerHTML = "I completed release 2.";
// Release 4:
var div_r_4 = document.getElementById('release-3');
div_r_4.style.backgroundColor = "#955251";
// Release 5:
var div_r_5 = document.getElementsByClassName("release-4");
for (var i = 0; i < div_r_5.length; i++) |
// Release 6:
var template = document.getElementById('hidden');
document.body.appendChild(template.content.cloneNode(true));
| {
div_r_5[i].style.fontSize = "2em";
} | conditional_block |
home_page.js | // DOM Manipulation Challenge
// I worked on this challenge with: Austin Dorff.
// Add your JavaScript calls to this page:
// Release 0:
// Set up
// Release 1:
var div_r_1 = document.getElementById("release-0");
div_r_1.className = "done";
// Release 2:
var div_r_2 = document.getElementById('release-1');
div_r_2.style.display = "none";
// Release 3:
var div_r_3 = document.getElementsByTagName('h1')[0];
div_r_3.innerHTML = "I completed release 2.";
// Release 4:
var div_r_4 = document.getElementById('release-3'); | // Release 5:
var div_r_5 = document.getElementsByClassName("release-4");
for (var i = 0; i < div_r_5.length; i++) {
div_r_5[i].style.fontSize = "2em";
}
// Release 6:
var template = document.getElementById('hidden');
document.body.appendChild(template.content.cloneNode(true)); | div_r_4.style.backgroundColor = "#955251";
| random_line_split |
ipset.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Authors:
# Thomas Woerner <twoerner@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 os.path
from firewall.core.prog import runProg
from firewall.core.logger import log
from firewall.functions import tempFile, readfile
from firewall.config import COMMANDS
IPSET_MAXNAMELEN = 32
IPSET_TYPES = [
# bitmap and set types are currently not supported
# "bitmap:ip",
# "bitmap:ip,mac",
# "bitmap:port",
# "list:set",
"hash:ip",
#"hash:ip,port",
#"hash:ip,port,ip",
#"hash:ip,port,net",
#"hash:ip,mark",
"hash:net",
#"hash:net,net",
#"hash:net,port",
#"hash:net,port,net",
#"hash:net,iface",
"hash:mac",
]
IPSET_CREATE_OPTIONS = {
"family": "inet|inet6",
"hashsize": "value",
"maxelem": "value",
"timeout": "value in secs",
# "counters": None,
# "comment": None,
}
class ipset:
def __init__(self):
self._command = COMMANDS["ipset"]
def __run(self, args):
# convert to string list
_args = ["%s" % item for item in args]
log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
(status, ret) = runProg(self._command, _args)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command, | return ret
def check_name(self, name):
if len(name) > IPSET_MAXNAMELEN:
raise FirewallError(INVALID_NAME,
"ipset name '%s' is not valid" % name)
def supported_types(self):
ret = { }
output = ""
try:
output = self.__run(["--help"])
except ValueError as e:
log.debug1("ipset error: %s" % e)
lines = output.splitlines()
in_types = False
for line in lines:
#print(line)
if in_types:
splits = line.strip().split(None, 2)
ret[splits[0]] = splits[2]
if line.startswith("Supported set types:"):
in_types = True
return ret
def check_type(self, type_name):
if len(type_name) > IPSET_MAXNAMELEN or type_name not in IPSET_TYPES:
raise FirewallError(INVALID_TYPE,
"ipset type name '%s' is not valid" % type_name)
def create(self, set_name, type_name, options=None):
self.check_name(set_name)
self.check_type(type_name)
args = [ "create", set_name, type_name ]
if options:
for k,v in options.items():
args.append(k)
if v != "":
args.append(v)
return self.__run(args)
def destroy(self, set_name):
self.check_name(set_name)
return self.__run([ "destroy", set_name ])
def add(self, set_name, entry, options=None):
args = [ "add", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def delete(self, set_name, entry, options=None):
args = [ "del", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def test(self, set_name, entry, options=None):
args = [ "test", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def list(self, set_name=None):
args = [ "list" ]
if set_name:
args.append(set_name)
return self.__run(args).split()
def save(self, set_name=None):
args = [ "save" ]
if set_name:
args.append(set_name)
return self.__run(args)
def restore(self, set_name, type_name, entries,
create_options=None, entry_options=None):
self.check_name(set_name)
self.check_type(type_name)
temp_file = tempFile()
if ' ' in set_name:
set_name = "'%s'" % set_name
args = [ "create", set_name, type_name, "-exist" ]
if create_options:
for k,v in create_options.items():
args.append(k)
if v != "":
args.append(v)
temp_file.write("%s\n" % " ".join(args))
for entry in entries:
if ' ' in entry:
entry = "'%s'" % entry
if entry_options:
temp_file.write("add %s %s %s\n" % (set_name, entry,
" ".join(entry_options)))
else:
temp_file.write("add %s %s\n" % (set_name, entry))
temp_file.close()
stat = os.stat(temp_file.name)
log.debug2("%s: %s restore %s", self.__class__, self._command,
"%s: %d" % (temp_file.name, stat.st_size))
args = [ "restore" ]
(status, ret) = runProg(self._command, args,
stdin=temp_file.name)
if log.getDebugLogLevel() > 2:
try:
lines = readfile(temp_file.name)
except:
pass
else:
i = 1
for line in readfile(temp_file.name):
log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
if not line.endswith("\n"):
log.debug3("", nofmt=1)
i += 1
os.unlink(temp_file.name)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(args), ret))
return ret
def flush(self, set_name):
args = [ "flush" ]
if set_name:
args.append(set_name)
return self.__run(args)
def rename(self, old_set_name, new_set_name):
return self.__run([ "rename", old_set_name, new_set_name ])
def swap(self, set_name_1, set_name_2):
return self.__run([ "swap", set_name_1, set_name_2 ])
def version(self):
return self.__run([ "version" ])
def check_ipset_name(ipset):
if len(ipset) > IPSET_MAXNAMELEN:
return False
return True | " ".join(_args), ret)) | random_line_split |
ipset.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Authors:
# Thomas Woerner <twoerner@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 os.path
from firewall.core.prog import runProg
from firewall.core.logger import log
from firewall.functions import tempFile, readfile
from firewall.config import COMMANDS
IPSET_MAXNAMELEN = 32
IPSET_TYPES = [
# bitmap and set types are currently not supported
# "bitmap:ip",
# "bitmap:ip,mac",
# "bitmap:port",
# "list:set",
"hash:ip",
#"hash:ip,port",
#"hash:ip,port,ip",
#"hash:ip,port,net",
#"hash:ip,mark",
"hash:net",
#"hash:net,net",
#"hash:net,port",
#"hash:net,port,net",
#"hash:net,iface",
"hash:mac",
]
IPSET_CREATE_OPTIONS = {
"family": "inet|inet6",
"hashsize": "value",
"maxelem": "value",
"timeout": "value in secs",
# "counters": None,
# "comment": None,
}
class ipset:
def __init__(self):
self._command = COMMANDS["ipset"]
def __run(self, args):
# convert to string list
_args = ["%s" % item for item in args]
log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
(status, ret) = runProg(self._command, _args)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(_args), ret))
return ret
def check_name(self, name):
if len(name) > IPSET_MAXNAMELEN:
raise FirewallError(INVALID_NAME,
"ipset name '%s' is not valid" % name)
def supported_types(self):
ret = { }
output = ""
try:
output = self.__run(["--help"])
except ValueError as e:
log.debug1("ipset error: %s" % e)
lines = output.splitlines()
in_types = False
for line in lines:
#print(line)
if in_types:
splits = line.strip().split(None, 2)
ret[splits[0]] = splits[2]
if line.startswith("Supported set types:"):
in_types = True
return ret
def check_type(self, type_name):
if len(type_name) > IPSET_MAXNAMELEN or type_name not in IPSET_TYPES:
raise FirewallError(INVALID_TYPE,
"ipset type name '%s' is not valid" % type_name)
def | (self, set_name, type_name, options=None):
self.check_name(set_name)
self.check_type(type_name)
args = [ "create", set_name, type_name ]
if options:
for k,v in options.items():
args.append(k)
if v != "":
args.append(v)
return self.__run(args)
def destroy(self, set_name):
self.check_name(set_name)
return self.__run([ "destroy", set_name ])
def add(self, set_name, entry, options=None):
args = [ "add", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def delete(self, set_name, entry, options=None):
args = [ "del", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def test(self, set_name, entry, options=None):
args = [ "test", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def list(self, set_name=None):
args = [ "list" ]
if set_name:
args.append(set_name)
return self.__run(args).split()
def save(self, set_name=None):
args = [ "save" ]
if set_name:
args.append(set_name)
return self.__run(args)
def restore(self, set_name, type_name, entries,
create_options=None, entry_options=None):
self.check_name(set_name)
self.check_type(type_name)
temp_file = tempFile()
if ' ' in set_name:
set_name = "'%s'" % set_name
args = [ "create", set_name, type_name, "-exist" ]
if create_options:
for k,v in create_options.items():
args.append(k)
if v != "":
args.append(v)
temp_file.write("%s\n" % " ".join(args))
for entry in entries:
if ' ' in entry:
entry = "'%s'" % entry
if entry_options:
temp_file.write("add %s %s %s\n" % (set_name, entry,
" ".join(entry_options)))
else:
temp_file.write("add %s %s\n" % (set_name, entry))
temp_file.close()
stat = os.stat(temp_file.name)
log.debug2("%s: %s restore %s", self.__class__, self._command,
"%s: %d" % (temp_file.name, stat.st_size))
args = [ "restore" ]
(status, ret) = runProg(self._command, args,
stdin=temp_file.name)
if log.getDebugLogLevel() > 2:
try:
lines = readfile(temp_file.name)
except:
pass
else:
i = 1
for line in readfile(temp_file.name):
log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
if not line.endswith("\n"):
log.debug3("", nofmt=1)
i += 1
os.unlink(temp_file.name)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(args), ret))
return ret
def flush(self, set_name):
args = [ "flush" ]
if set_name:
args.append(set_name)
return self.__run(args)
def rename(self, old_set_name, new_set_name):
return self.__run([ "rename", old_set_name, new_set_name ])
def swap(self, set_name_1, set_name_2):
return self.__run([ "swap", set_name_1, set_name_2 ])
def version(self):
return self.__run([ "version" ])
def check_ipset_name(ipset):
if len(ipset) > IPSET_MAXNAMELEN:
return False
return True
| create | identifier_name |
ipset.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Authors:
# Thomas Woerner <twoerner@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 os.path
from firewall.core.prog import runProg
from firewall.core.logger import log
from firewall.functions import tempFile, readfile
from firewall.config import COMMANDS
IPSET_MAXNAMELEN = 32
IPSET_TYPES = [
# bitmap and set types are currently not supported
# "bitmap:ip",
# "bitmap:ip,mac",
# "bitmap:port",
# "list:set",
"hash:ip",
#"hash:ip,port",
#"hash:ip,port,ip",
#"hash:ip,port,net",
#"hash:ip,mark",
"hash:net",
#"hash:net,net",
#"hash:net,port",
#"hash:net,port,net",
#"hash:net,iface",
"hash:mac",
]
IPSET_CREATE_OPTIONS = {
"family": "inet|inet6",
"hashsize": "value",
"maxelem": "value",
"timeout": "value in secs",
# "counters": None,
# "comment": None,
}
class ipset:
|
def check_ipset_name(ipset):
if len(ipset) > IPSET_MAXNAMELEN:
return False
return True
| def __init__(self):
self._command = COMMANDS["ipset"]
def __run(self, args):
# convert to string list
_args = ["%s" % item for item in args]
log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
(status, ret) = runProg(self._command, _args)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(_args), ret))
return ret
def check_name(self, name):
if len(name) > IPSET_MAXNAMELEN:
raise FirewallError(INVALID_NAME,
"ipset name '%s' is not valid" % name)
def supported_types(self):
ret = { }
output = ""
try:
output = self.__run(["--help"])
except ValueError as e:
log.debug1("ipset error: %s" % e)
lines = output.splitlines()
in_types = False
for line in lines:
#print(line)
if in_types:
splits = line.strip().split(None, 2)
ret[splits[0]] = splits[2]
if line.startswith("Supported set types:"):
in_types = True
return ret
def check_type(self, type_name):
if len(type_name) > IPSET_MAXNAMELEN or type_name not in IPSET_TYPES:
raise FirewallError(INVALID_TYPE,
"ipset type name '%s' is not valid" % type_name)
def create(self, set_name, type_name, options=None):
self.check_name(set_name)
self.check_type(type_name)
args = [ "create", set_name, type_name ]
if options:
for k,v in options.items():
args.append(k)
if v != "":
args.append(v)
return self.__run(args)
def destroy(self, set_name):
self.check_name(set_name)
return self.__run([ "destroy", set_name ])
def add(self, set_name, entry, options=None):
args = [ "add", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def delete(self, set_name, entry, options=None):
args = [ "del", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def test(self, set_name, entry, options=None):
args = [ "test", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def list(self, set_name=None):
args = [ "list" ]
if set_name:
args.append(set_name)
return self.__run(args).split()
def save(self, set_name=None):
args = [ "save" ]
if set_name:
args.append(set_name)
return self.__run(args)
def restore(self, set_name, type_name, entries,
create_options=None, entry_options=None):
self.check_name(set_name)
self.check_type(type_name)
temp_file = tempFile()
if ' ' in set_name:
set_name = "'%s'" % set_name
args = [ "create", set_name, type_name, "-exist" ]
if create_options:
for k,v in create_options.items():
args.append(k)
if v != "":
args.append(v)
temp_file.write("%s\n" % " ".join(args))
for entry in entries:
if ' ' in entry:
entry = "'%s'" % entry
if entry_options:
temp_file.write("add %s %s %s\n" % (set_name, entry,
" ".join(entry_options)))
else:
temp_file.write("add %s %s\n" % (set_name, entry))
temp_file.close()
stat = os.stat(temp_file.name)
log.debug2("%s: %s restore %s", self.__class__, self._command,
"%s: %d" % (temp_file.name, stat.st_size))
args = [ "restore" ]
(status, ret) = runProg(self._command, args,
stdin=temp_file.name)
if log.getDebugLogLevel() > 2:
try:
lines = readfile(temp_file.name)
except:
pass
else:
i = 1
for line in readfile(temp_file.name):
log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
if not line.endswith("\n"):
log.debug3("", nofmt=1)
i += 1
os.unlink(temp_file.name)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(args), ret))
return ret
def flush(self, set_name):
args = [ "flush" ]
if set_name:
args.append(set_name)
return self.__run(args)
def rename(self, old_set_name, new_set_name):
return self.__run([ "rename", old_set_name, new_set_name ])
def swap(self, set_name_1, set_name_2):
return self.__run([ "swap", set_name_1, set_name_2 ])
def version(self):
return self.__run([ "version" ]) | identifier_body |
ipset.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Authors:
# Thomas Woerner <twoerner@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 os.path
from firewall.core.prog import runProg
from firewall.core.logger import log
from firewall.functions import tempFile, readfile
from firewall.config import COMMANDS
IPSET_MAXNAMELEN = 32
IPSET_TYPES = [
# bitmap and set types are currently not supported
# "bitmap:ip",
# "bitmap:ip,mac",
# "bitmap:port",
# "list:set",
"hash:ip",
#"hash:ip,port",
#"hash:ip,port,ip",
#"hash:ip,port,net",
#"hash:ip,mark",
"hash:net",
#"hash:net,net",
#"hash:net,port",
#"hash:net,port,net",
#"hash:net,iface",
"hash:mac",
]
IPSET_CREATE_OPTIONS = {
"family": "inet|inet6",
"hashsize": "value",
"maxelem": "value",
"timeout": "value in secs",
# "counters": None,
# "comment": None,
}
class ipset:
def __init__(self):
self._command = COMMANDS["ipset"]
def __run(self, args):
# convert to string list
_args = ["%s" % item for item in args]
log.debug2("%s: %s %s", self.__class__, self._command, " ".join(_args))
(status, ret) = runProg(self._command, _args)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(_args), ret))
return ret
def check_name(self, name):
if len(name) > IPSET_MAXNAMELEN:
raise FirewallError(INVALID_NAME,
"ipset name '%s' is not valid" % name)
def supported_types(self):
ret = { }
output = ""
try:
output = self.__run(["--help"])
except ValueError as e:
log.debug1("ipset error: %s" % e)
lines = output.splitlines()
in_types = False
for line in lines:
#print(line)
|
return ret
def check_type(self, type_name):
if len(type_name) > IPSET_MAXNAMELEN or type_name not in IPSET_TYPES:
raise FirewallError(INVALID_TYPE,
"ipset type name '%s' is not valid" % type_name)
def create(self, set_name, type_name, options=None):
self.check_name(set_name)
self.check_type(type_name)
args = [ "create", set_name, type_name ]
if options:
for k,v in options.items():
args.append(k)
if v != "":
args.append(v)
return self.__run(args)
def destroy(self, set_name):
self.check_name(set_name)
return self.__run([ "destroy", set_name ])
def add(self, set_name, entry, options=None):
args = [ "add", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def delete(self, set_name, entry, options=None):
args = [ "del", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def test(self, set_name, entry, options=None):
args = [ "test", set_name, entry ]
if options:
args.append("%s" % " ".join(options))
return self.__run(args)
def list(self, set_name=None):
args = [ "list" ]
if set_name:
args.append(set_name)
return self.__run(args).split()
def save(self, set_name=None):
args = [ "save" ]
if set_name:
args.append(set_name)
return self.__run(args)
def restore(self, set_name, type_name, entries,
create_options=None, entry_options=None):
self.check_name(set_name)
self.check_type(type_name)
temp_file = tempFile()
if ' ' in set_name:
set_name = "'%s'" % set_name
args = [ "create", set_name, type_name, "-exist" ]
if create_options:
for k,v in create_options.items():
args.append(k)
if v != "":
args.append(v)
temp_file.write("%s\n" % " ".join(args))
for entry in entries:
if ' ' in entry:
entry = "'%s'" % entry
if entry_options:
temp_file.write("add %s %s %s\n" % (set_name, entry,
" ".join(entry_options)))
else:
temp_file.write("add %s %s\n" % (set_name, entry))
temp_file.close()
stat = os.stat(temp_file.name)
log.debug2("%s: %s restore %s", self.__class__, self._command,
"%s: %d" % (temp_file.name, stat.st_size))
args = [ "restore" ]
(status, ret) = runProg(self._command, args,
stdin=temp_file.name)
if log.getDebugLogLevel() > 2:
try:
lines = readfile(temp_file.name)
except:
pass
else:
i = 1
for line in readfile(temp_file.name):
log.debug3("%8d: %s" % (i, line), nofmt=1, nl=0)
if not line.endswith("\n"):
log.debug3("", nofmt=1)
i += 1
os.unlink(temp_file.name)
if status != 0:
raise ValueError("'%s %s' failed: %s" % (self._command,
" ".join(args), ret))
return ret
def flush(self, set_name):
args = [ "flush" ]
if set_name:
args.append(set_name)
return self.__run(args)
def rename(self, old_set_name, new_set_name):
return self.__run([ "rename", old_set_name, new_set_name ])
def swap(self, set_name_1, set_name_2):
return self.__run([ "swap", set_name_1, set_name_2 ])
def version(self):
return self.__run([ "version" ])
def check_ipset_name(ipset):
if len(ipset) > IPSET_MAXNAMELEN:
return False
return True
| if in_types:
splits = line.strip().split(None, 2)
ret[splits[0]] = splits[2]
if line.startswith("Supported set types:"):
in_types = True | conditional_block |
autowrapped_static_text.py | # -*- coding: utf-8 -*-
import wx
from copy import copy
sWhitespace = ' \t\n'
def SplitAndKeep(string, splitchars = " \t\n"):
substrs = []
i = 0
while len(string) > 0:
if string[i] in splitchars:
substrs.append(string[:i])
substrs.append(string[i])
string = string[i+1:]
i = 0
else:
i += 1
if i >= len(string):
substrs.append(string)
break
return substrs
class AutowrappedStaticText(wx.StaticText):
"""A StaticText-like widget which implements word wrapping."""
def __init__(self, *args, **kwargs):
wx.StaticText.__init__(self, *args, **kwargs)
self.label = super(AutowrappedStaticText, self).GetLabel()
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.lastWrap = None
self.Wrap()
def SetLabel(self, newLabel):
"""Store the new label and recalculate the wrapped version."""
self.label = newLabel
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Wrap()
def GetLabel(self):
"""Returns the label (unwrapped)."""
return self.label
def Wrap(self):
"""Wraps the words in label."""
maxWidth = self.GetParent().GetVirtualSizeTuple()[0] - 10
#TODO: Fix this so that we're not wasting cycles, but so that it actually works
#if self.lastWrap and self.lastWrap == maxWidth:
# return
self.lastWrap = maxWidth
pieces = copy(self.pieces)
lines = []
currentLine = []
currentString = ""
while len(pieces) > 0:
nextPiece = pieces.pop(0)
newString = currentString + nextPiece
newWidth = self.GetTextExtent(newString)[0]
currentPieceCount = len(currentLine)
if (currentPieceCount > 0 and newWidth > maxWidth) or nextPiece == '\n':
if currentPieceCount > 0 and currentLine[-1] in sWhitespace:
currentLine = currentLine[:-1]
if nextPiece in sWhitespace:
|
currentLine.append('\n')
lines.extend(currentLine)
currentLine = [nextPiece]
currentString = nextPiece
else:
currentString += nextPiece
currentLine.append(nextPiece)
lines.extend(currentLine)
line = "".join(lines)
super(AutowrappedStaticText, self).SetLabel(line)
self.Refresh()
def OnSize(self, event):
self.Wrap()
| pieces = pieces[1:] | conditional_block |
autowrapped_static_text.py | # -*- coding: utf-8 -*-
import wx
from copy import copy
sWhitespace = ' \t\n'
def SplitAndKeep(string, splitchars = " \t\n"):
substrs = []
i = 0
while len(string) > 0:
if string[i] in splitchars:
substrs.append(string[:i])
substrs.append(string[i])
string = string[i+1:]
i = 0
else:
i += 1
if i >= len(string):
substrs.append(string)
break
return substrs
class AutowrappedStaticText(wx.StaticText):
| """A StaticText-like widget which implements word wrapping."""
def __init__(self, *args, **kwargs):
wx.StaticText.__init__(self, *args, **kwargs)
self.label = super(AutowrappedStaticText, self).GetLabel()
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.lastWrap = None
self.Wrap()
def SetLabel(self, newLabel):
"""Store the new label and recalculate the wrapped version."""
self.label = newLabel
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Wrap()
def GetLabel(self):
"""Returns the label (unwrapped)."""
return self.label
def Wrap(self):
"""Wraps the words in label."""
maxWidth = self.GetParent().GetVirtualSizeTuple()[0] - 10
#TODO: Fix this so that we're not wasting cycles, but so that it actually works
#if self.lastWrap and self.lastWrap == maxWidth:
# return
self.lastWrap = maxWidth
pieces = copy(self.pieces)
lines = []
currentLine = []
currentString = ""
while len(pieces) > 0:
nextPiece = pieces.pop(0)
newString = currentString + nextPiece
newWidth = self.GetTextExtent(newString)[0]
currentPieceCount = len(currentLine)
if (currentPieceCount > 0 and newWidth > maxWidth) or nextPiece == '\n':
if currentPieceCount > 0 and currentLine[-1] in sWhitespace:
currentLine = currentLine[:-1]
if nextPiece in sWhitespace:
pieces = pieces[1:]
currentLine.append('\n')
lines.extend(currentLine)
currentLine = [nextPiece]
currentString = nextPiece
else:
currentString += nextPiece
currentLine.append(nextPiece)
lines.extend(currentLine)
line = "".join(lines)
super(AutowrappedStaticText, self).SetLabel(line)
self.Refresh()
def OnSize(self, event):
self.Wrap() | identifier_body | |
autowrapped_static_text.py | # -*- coding: utf-8 -*-
import wx
from copy import copy
sWhitespace = ' \t\n'
def SplitAndKeep(string, splitchars = " \t\n"):
substrs = []
i = 0
while len(string) > 0:
if string[i] in splitchars:
substrs.append(string[:i])
substrs.append(string[i])
string = string[i+1:]
i = 0
else:
i += 1
if i >= len(string):
substrs.append(string)
break
return substrs
class AutowrappedStaticText(wx.StaticText):
"""A StaticText-like widget which implements word wrapping."""
def __init__(self, *args, **kwargs):
wx.StaticText.__init__(self, *args, **kwargs)
self.label = super(AutowrappedStaticText, self).GetLabel() |
def SetLabel(self, newLabel):
"""Store the new label and recalculate the wrapped version."""
self.label = newLabel
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Wrap()
def GetLabel(self):
"""Returns the label (unwrapped)."""
return self.label
def Wrap(self):
"""Wraps the words in label."""
maxWidth = self.GetParent().GetVirtualSizeTuple()[0] - 10
#TODO: Fix this so that we're not wasting cycles, but so that it actually works
#if self.lastWrap and self.lastWrap == maxWidth:
# return
self.lastWrap = maxWidth
pieces = copy(self.pieces)
lines = []
currentLine = []
currentString = ""
while len(pieces) > 0:
nextPiece = pieces.pop(0)
newString = currentString + nextPiece
newWidth = self.GetTextExtent(newString)[0]
currentPieceCount = len(currentLine)
if (currentPieceCount > 0 and newWidth > maxWidth) or nextPiece == '\n':
if currentPieceCount > 0 and currentLine[-1] in sWhitespace:
currentLine = currentLine[:-1]
if nextPiece in sWhitespace:
pieces = pieces[1:]
currentLine.append('\n')
lines.extend(currentLine)
currentLine = [nextPiece]
currentString = nextPiece
else:
currentString += nextPiece
currentLine.append(nextPiece)
lines.extend(currentLine)
line = "".join(lines)
super(AutowrappedStaticText, self).SetLabel(line)
self.Refresh()
def OnSize(self, event):
self.Wrap() | self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.lastWrap = None
self.Wrap() | random_line_split |
autowrapped_static_text.py | # -*- coding: utf-8 -*-
import wx
from copy import copy
sWhitespace = ' \t\n'
def | (string, splitchars = " \t\n"):
substrs = []
i = 0
while len(string) > 0:
if string[i] in splitchars:
substrs.append(string[:i])
substrs.append(string[i])
string = string[i+1:]
i = 0
else:
i += 1
if i >= len(string):
substrs.append(string)
break
return substrs
class AutowrappedStaticText(wx.StaticText):
"""A StaticText-like widget which implements word wrapping."""
def __init__(self, *args, **kwargs):
wx.StaticText.__init__(self, *args, **kwargs)
self.label = super(AutowrappedStaticText, self).GetLabel()
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.lastWrap = None
self.Wrap()
def SetLabel(self, newLabel):
"""Store the new label and recalculate the wrapped version."""
self.label = newLabel
self.pieces = SplitAndKeep(self.label, sWhitespace)
self.Wrap()
def GetLabel(self):
"""Returns the label (unwrapped)."""
return self.label
def Wrap(self):
"""Wraps the words in label."""
maxWidth = self.GetParent().GetVirtualSizeTuple()[0] - 10
#TODO: Fix this so that we're not wasting cycles, but so that it actually works
#if self.lastWrap and self.lastWrap == maxWidth:
# return
self.lastWrap = maxWidth
pieces = copy(self.pieces)
lines = []
currentLine = []
currentString = ""
while len(pieces) > 0:
nextPiece = pieces.pop(0)
newString = currentString + nextPiece
newWidth = self.GetTextExtent(newString)[0]
currentPieceCount = len(currentLine)
if (currentPieceCount > 0 and newWidth > maxWidth) or nextPiece == '\n':
if currentPieceCount > 0 and currentLine[-1] in sWhitespace:
currentLine = currentLine[:-1]
if nextPiece in sWhitespace:
pieces = pieces[1:]
currentLine.append('\n')
lines.extend(currentLine)
currentLine = [nextPiece]
currentString = nextPiece
else:
currentString += nextPiece
currentLine.append(nextPiece)
lines.extend(currentLine)
line = "".join(lines)
super(AutowrappedStaticText, self).SetLabel(line)
self.Refresh()
def OnSize(self, event):
self.Wrap()
| SplitAndKeep | identifier_name |
shadowroot.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootMode;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding, UnbindContext};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
use style::stylist::CascadeData;
/// Whether a shadow root hosts an User Agent widget.
#[derive(JSTraceable, MallocSizeOf, PartialEq)]
pub enum IsUserAgentWidget {
No,
Yes,
}
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: MutNullableDom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: MutNullableDom::new(Some(host)),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
)
}
pub fn detach(&self) {
self.document.unregister_shadow_root(&self);
let node = self.upcast::<Node>();
node.set_containing_shadow_root(None);
Node::complete_remove_subtree(&node, &UnbindContext::new(node, None, None, None));
self.host.set(None);
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> |
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
if let Some(host) = self.host.get() {
host.upcast::<Node>().dirty(NodeDamage::NodeStyleDamaged);
}
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_element_id(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_element_id(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
let host = self.host.get();
host.expect("Trying to get host from a detached shadow root")
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers<'dom> {
fn get_host_for_layout(self) -> LayoutDom<'dom, Element>;
fn get_style_data_for_layout(self) -> &'dom CascadeData;
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl<'dom> LayoutShadowRootHelpers<'dom> for LayoutDom<'dom, ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
fn get_host_for_layout(self) -> LayoutDom<'dom, Element> {
unsafe {
self.unsafe_get()
.host
.get_inner_as_layout()
.expect("We should never do layout on a detached shadow root")
}
}
#[inline]
#[allow(unsafe_code)]
fn get_style_data_for_layout(self) -> &'dom CascadeData {
fn is_sync<T: Sync>() {}
let _ = is_sync::<CascadeData>;
unsafe { &self.unsafe_get().author_styles.borrow_for_layout().data }
}
// FIXME(nox): This uses the dreaded borrow_mut_for_layout so this should
// probably be revisited.
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
| {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
} | identifier_body |
shadowroot.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootMode;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding, UnbindContext};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
use style::stylist::CascadeData;
/// Whether a shadow root hosts an User Agent widget.
#[derive(JSTraceable, MallocSizeOf, PartialEq)]
pub enum IsUserAgentWidget {
No,
Yes,
}
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: MutNullableDom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: MutNullableDom::new(Some(host)),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
)
}
pub fn detach(&self) {
self.document.unregister_shadow_root(&self);
let node = self.upcast::<Node>();
node.set_containing_shadow_root(None);
Node::complete_remove_subtree(&node, &UnbindContext::new(node, None, None, None));
self.host.set(None);
}
pub fn | (&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
if let Some(host) = self.host.get() {
host.upcast::<Node>().dirty(NodeDamage::NodeStyleDamaged);
}
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_element_id(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_element_id(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
let host = self.host.get();
host.expect("Trying to get host from a detached shadow root")
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers<'dom> {
fn get_host_for_layout(self) -> LayoutDom<'dom, Element>;
fn get_style_data_for_layout(self) -> &'dom CascadeData;
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl<'dom> LayoutShadowRootHelpers<'dom> for LayoutDom<'dom, ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
fn get_host_for_layout(self) -> LayoutDom<'dom, Element> {
unsafe {
self.unsafe_get()
.host
.get_inner_as_layout()
.expect("We should never do layout on a detached shadow root")
}
}
#[inline]
#[allow(unsafe_code)]
fn get_style_data_for_layout(self) -> &'dom CascadeData {
fn is_sync<T: Sync>() {}
let _ = is_sync::<CascadeData>;
unsafe { &self.unsafe_get().author_styles.borrow_for_layout().data }
}
// FIXME(nox): This uses the dreaded borrow_mut_for_layout so this should
// probably be revisited.
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
| get_focused_element | identifier_name |
shadowroot.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootMode;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding, UnbindContext};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
use style::stylist::CascadeData;
/// Whether a shadow root hosts an User Agent widget.
#[derive(JSTraceable, MallocSizeOf, PartialEq)]
pub enum IsUserAgentWidget {
No,
Yes,
}
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: MutNullableDom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: MutNullableDom::new(Some(host)),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
)
}
pub fn detach(&self) {
self.document.unregister_shadow_root(&self);
let node = self.upcast::<Node>();
node.set_containing_shadow_root(None);
Node::complete_remove_subtree(&node, &UnbindContext::new(node, None, None, None));
self.host.set(None);
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
}
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
if let Some(host) = self.host.get() {
host.upcast::<Node>().dirty(NodeDamage::NodeStyleDamaged);
}
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_element_id(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_element_id(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => | ,
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
let host = self.host.get();
host.expect("Trying to get host from a detached shadow root")
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers<'dom> {
fn get_host_for_layout(self) -> LayoutDom<'dom, Element>;
fn get_style_data_for_layout(self) -> &'dom CascadeData;
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl<'dom> LayoutShadowRootHelpers<'dom> for LayoutDom<'dom, ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
fn get_host_for_layout(self) -> LayoutDom<'dom, Element> {
unsafe {
self.unsafe_get()
.host
.get_inner_as_layout()
.expect("We should never do layout on a detached shadow root")
}
}
#[inline]
#[allow(unsafe_code)]
fn get_style_data_for_layout(self) -> &'dom CascadeData {
fn is_sync<T: Sync>() {}
let _ = is_sync::<CascadeData>;
unsafe { &self.unsafe_get().author_styles.borrow_for_layout().data }
}
// FIXME(nox): This uses the dreaded borrow_mut_for_layout so this should
// probably be revisited.
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
}
| {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
} | conditional_block |
shadowroot.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootBinding::ShadowRootMethods;
use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRootMode;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
use crate::dom::cssstylesheet::CSSStyleSheet;
use crate::dom::document::Document;
use crate::dom::documentfragment::DocumentFragment;
use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument};
use crate::dom::element::Element;
use crate::dom::node::{Node, NodeDamage, NodeFlags, ShadowIncluding, UnbindContext};
use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
use crate::dom::window::Window;
use crate::stylesheet_set::StylesheetSetRef;
use dom_struct::dom_struct;
use selectors::context::QuirksMode;
use servo_arc::Arc;
use servo_atoms::Atom;
use style::author_styles::AuthorStyles;
use style::dom::TElement;
use style::media_queries::Device;
use style::shared_lock::SharedRwLockReadGuard;
use style::stylesheets::Stylesheet;
use style::stylist::CascadeData;
/// Whether a shadow root hosts an User Agent widget.
#[derive(JSTraceable, MallocSizeOf, PartialEq)]
pub enum IsUserAgentWidget {
No,
Yes,
}
// https://dom.spec.whatwg.org/#interface-shadowroot
#[dom_struct]
pub struct ShadowRoot {
document_fragment: DocumentFragment,
document_or_shadow_root: DocumentOrShadowRoot,
document: Dom<Document>,
host: MutNullableDom<Element>,
/// List of author styles associated with nodes in this shadow tree.
author_styles: DomRefCell<AuthorStyles<StyleSheetInDocument>>,
stylesheet_list: MutNullableDom<StyleSheetList>,
window: Dom<Window>,
}
impl ShadowRoot {
#[allow(unrooted_must_root)]
fn new_inherited(host: &Element, document: &Document) -> ShadowRoot {
let document_fragment = DocumentFragment::new_inherited(document);
let node = document_fragment.upcast::<Node>();
node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
node.set_flag(
NodeFlags::IS_CONNECTED,
host.upcast::<Node>().is_connected(),
);
ShadowRoot {
document_fragment,
document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
document: Dom::from_ref(document),
host: MutNullableDom::new(Some(host)),
author_styles: DomRefCell::new(AuthorStyles::new()),
stylesheet_list: MutNullableDom::new(None),
window: Dom::from_ref(document.window()),
}
}
pub fn new(host: &Element, document: &Document) -> DomRoot<ShadowRoot> {
reflect_dom_object(
Box::new(ShadowRoot::new_inherited(host, document)),
document.window(),
)
}
pub fn detach(&self) {
self.document.unregister_shadow_root(&self);
let node = self.upcast::<Node>();
node.set_containing_shadow_root(None);
Node::complete_remove_subtree(&node, &UnbindContext::new(node, None, None, None));
self.host.set(None);
}
pub fn get_focused_element(&self) -> Option<DomRoot<Element>> {
//XXX get retargeted focused element
None
} |
pub fn stylesheet_count(&self) -> usize {
self.author_styles.borrow().stylesheets.len()
}
pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
let stylesheets = &self.author_styles.borrow().stylesheets;
stylesheets
.get(index)
.and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet())
}
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the
/// correct tree position.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) {
let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
let insertion_point = stylesheets
.iter()
.find(|sheet_in_shadow| {
owner
.upcast::<Node>()
.is_before(sheet_in_shadow.owner.upcast())
})
.cloned();
DocumentOrShadowRoot::add_stylesheet(
owner,
StylesheetSetRef::Author(stylesheets),
sheet,
insertion_point,
self.document.style_shared_lock(),
);
}
/// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
#[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily.
pub fn remove_stylesheet(&self, owner: &Element, s: &Arc<Stylesheet>) {
DocumentOrShadowRoot::remove_stylesheet(
owner,
s,
StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
)
}
pub fn invalidate_stylesheets(&self) {
self.document.invalidate_shadow_roots_stylesheets();
self.author_styles.borrow_mut().stylesheets.force_dirty();
// Mark the host element dirty so a reflow will be performed.
if let Some(host) = self.host.get() {
host.upcast::<Node>().dirty(NodeDamage::NodeStyleDamaged);
}
}
/// Remove any existing association between the provided id and any elements
/// in this shadow tree.
pub fn unregister_element_id(&self, to_unregister: &Element, id: Atom) {
self.document_or_shadow_root.unregister_named_element(
self.document_fragment.id_map(),
to_unregister,
&id,
);
}
/// Associate an element present in this shadow tree with the provided id.
pub fn register_element_id(&self, element: &Element, id: Atom) {
let root = self
.upcast::<Node>()
.inclusive_ancestors(ShadowIncluding::No)
.last()
.unwrap();
self.document_or_shadow_root.register_named_element(
self.document_fragment.id_map(),
element,
&id,
root,
);
}
}
impl ShadowRootMethods for ShadowRoot {
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
self.document_or_shadow_root
.get_active_element(self.get_focused_element(), None, None)
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input.
match self.document_or_shadow_root.element_from_point(
x,
y,
None,
self.document.has_browsing_context(),
) {
Some(e) => {
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
},
None => None,
}
}
// https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
// Return the result of running the retargeting algorithm with context object
// and the original result as input
let mut elements = Vec::new();
for e in self
.document_or_shadow_root
.elements_from_point(x, y, None, self.document.has_browsing_context())
.iter()
{
let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>());
if let Some(element) = retargeted_node
.downcast::<Element>()
.map(|n| DomRoot::from_ref(n))
{
elements.push(element);
}
}
elements
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-mode
fn Mode(&self) -> ShadowRootMode {
ShadowRootMode::Closed
}
/// https://dom.spec.whatwg.org/#dom-shadowroot-host
fn Host(&self) -> DomRoot<Element> {
let host = self.host.get();
host.expect("Trying to get host from a detached shadow root")
}
// https://drafts.csswg.org/cssom/#dom-document-stylesheets
fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
self.stylesheet_list.or_init(|| {
StyleSheetList::new(
&self.window,
StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
)
})
}
}
#[allow(unsafe_code)]
pub trait LayoutShadowRootHelpers<'dom> {
fn get_host_for_layout(self) -> LayoutDom<'dom, Element>;
fn get_style_data_for_layout(self) -> &'dom CascadeData;
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
);
}
impl<'dom> LayoutShadowRootHelpers<'dom> for LayoutDom<'dom, ShadowRoot> {
#[inline]
#[allow(unsafe_code)]
fn get_host_for_layout(self) -> LayoutDom<'dom, Element> {
unsafe {
self.unsafe_get()
.host
.get_inner_as_layout()
.expect("We should never do layout on a detached shadow root")
}
}
#[inline]
#[allow(unsafe_code)]
fn get_style_data_for_layout(self) -> &'dom CascadeData {
fn is_sync<T: Sync>() {}
let _ = is_sync::<CascadeData>;
unsafe { &self.unsafe_get().author_styles.borrow_for_layout().data }
}
// FIXME(nox): This uses the dreaded borrow_mut_for_layout so this should
// probably be revisited.
#[inline]
#[allow(unsafe_code)]
unsafe fn flush_stylesheets<E: TElement>(
self,
device: &Device,
quirks_mode: QuirksMode,
guard: &SharedRwLockReadGuard,
) {
let mut author_styles = (*self.unsafe_get()).author_styles.borrow_mut_for_layout();
if author_styles.stylesheets.dirty() {
author_styles.flush::<E>(device, quirks_mode, guard);
}
}
} | random_line_split | |
selectors.py | '''
@since: 2015-01-07
@author: moschlar
'''
import sqlalchemy.types as sqlat
import tw2.core as twc | from sauce.widgets.widgets import (LargeMixin, SmallMixin, AdvancedWysihtml5,
MediumTextField, SmallTextField, CalendarDateTimePicker)
from sauce.widgets.validators import AdvancedWysihtml5BleachValidator
class ChosenPropertyMultipleSelectField(LargeMixin, twjc.ChosenMultipleSelectField, sw.PropertyMultipleSelectField):
search_contains = True
def _validate(self, value, state=None):
value = super(ChosenPropertyMultipleSelectField, self)._validate(value, state)
if self.required and not value:
raise twc.ValidationError('Please select at least one value')
else:
return value
class ChosenPropertySingleSelectField(SmallMixin, twjc.ChosenSingleSelectField, sw.PropertySingleSelectField):
search_contains = True
class MyWidgetSelector(SAWidgetSelector):
'''Custom WidgetSelector for SAUCE
Primarily uses fields from tw2.bootstrap.forms and tw2.jqplugins.chosen.
'''
text_field_limit = 256
default_multiple_select_field_widget_type = ChosenPropertyMultipleSelectField
default_single_select_field_widget_type = ChosenPropertySingleSelectField
default_name_based_widgets = {
'name': MediumTextField,
'subject': MediumTextField,
'_url': MediumTextField,
'user_name': MediumTextField,
'email_address': MediumTextField,
'_display_name': MediumTextField,
'description': AdvancedWysihtml5,
'message': AdvancedWysihtml5,
}
def __init__(self, *args, **kwargs):
self.default_widgets.update({
sqlat.String: MediumTextField,
sqlat.Integer: SmallTextField,
sqlat.Numeric: SmallTextField,
sqlat.DateTime: CalendarDateTimePicker,
sqlat.Date: twb.CalendarDatePicker,
sqlat.Time: twb.CalendarTimePicker,
sqlat.Binary: twb.FileField,
sqlat.BLOB: twb.FileField,
sqlat.PickleType: MediumTextField,
sqlat.Enum: twjc.ChosenSingleSelectField,
})
super(MyWidgetSelector, self).__init__(*args, **kwargs)
def select(self, field):
widget = super(MyWidgetSelector, self).select(field)
if (issubclass(widget, sw.TextArea)
and hasattr(field.type, 'length')
and (field.type.length is None or field.type.length < self.text_field_limit)):
widget = MediumTextField
return widget
class MyValidatorSelector(SAValidatorSelector):
_name_based_validators = {
'email_address': Email,
'description': AdvancedWysihtml5BleachValidator,
'message': AdvancedWysihtml5BleachValidator,
}
# def select(self, field):
# print 'MyValidatorSelector', 'select', field
# return super(MyValidatorSelector, self).select(field) | import tw2.bootstrap.forms as twb
import tw2.jqplugins.chosen.widgets as twjc
import sprox.widgets.tw2widgets.widgets as sw
from sprox.sa.widgetselector import SAWidgetSelector
from sprox.sa.validatorselector import SAValidatorSelector, Email | random_line_split |
selectors.py | '''
@since: 2015-01-07
@author: moschlar
'''
import sqlalchemy.types as sqlat
import tw2.core as twc
import tw2.bootstrap.forms as twb
import tw2.jqplugins.chosen.widgets as twjc
import sprox.widgets.tw2widgets.widgets as sw
from sprox.sa.widgetselector import SAWidgetSelector
from sprox.sa.validatorselector import SAValidatorSelector, Email
from sauce.widgets.widgets import (LargeMixin, SmallMixin, AdvancedWysihtml5,
MediumTextField, SmallTextField, CalendarDateTimePicker)
from sauce.widgets.validators import AdvancedWysihtml5BleachValidator
class ChosenPropertyMultipleSelectField(LargeMixin, twjc.ChosenMultipleSelectField, sw.PropertyMultipleSelectField):
search_contains = True
def _validate(self, value, state=None):
value = super(ChosenPropertyMultipleSelectField, self)._validate(value, state)
if self.required and not value:
raise twc.ValidationError('Please select at least one value')
else:
|
class ChosenPropertySingleSelectField(SmallMixin, twjc.ChosenSingleSelectField, sw.PropertySingleSelectField):
search_contains = True
class MyWidgetSelector(SAWidgetSelector):
'''Custom WidgetSelector for SAUCE
Primarily uses fields from tw2.bootstrap.forms and tw2.jqplugins.chosen.
'''
text_field_limit = 256
default_multiple_select_field_widget_type = ChosenPropertyMultipleSelectField
default_single_select_field_widget_type = ChosenPropertySingleSelectField
default_name_based_widgets = {
'name': MediumTextField,
'subject': MediumTextField,
'_url': MediumTextField,
'user_name': MediumTextField,
'email_address': MediumTextField,
'_display_name': MediumTextField,
'description': AdvancedWysihtml5,
'message': AdvancedWysihtml5,
}
def __init__(self, *args, **kwargs):
self.default_widgets.update({
sqlat.String: MediumTextField,
sqlat.Integer: SmallTextField,
sqlat.Numeric: SmallTextField,
sqlat.DateTime: CalendarDateTimePicker,
sqlat.Date: twb.CalendarDatePicker,
sqlat.Time: twb.CalendarTimePicker,
sqlat.Binary: twb.FileField,
sqlat.BLOB: twb.FileField,
sqlat.PickleType: MediumTextField,
sqlat.Enum: twjc.ChosenSingleSelectField,
})
super(MyWidgetSelector, self).__init__(*args, **kwargs)
def select(self, field):
widget = super(MyWidgetSelector, self).select(field)
if (issubclass(widget, sw.TextArea)
and hasattr(field.type, 'length')
and (field.type.length is None or field.type.length < self.text_field_limit)):
widget = MediumTextField
return widget
class MyValidatorSelector(SAValidatorSelector):
_name_based_validators = {
'email_address': Email,
'description': AdvancedWysihtml5BleachValidator,
'message': AdvancedWysihtml5BleachValidator,
}
# def select(self, field):
# print 'MyValidatorSelector', 'select', field
# return super(MyValidatorSelector, self).select(field)
| return value | conditional_block |
selectors.py | '''
@since: 2015-01-07
@author: moschlar
'''
import sqlalchemy.types as sqlat
import tw2.core as twc
import tw2.bootstrap.forms as twb
import tw2.jqplugins.chosen.widgets as twjc
import sprox.widgets.tw2widgets.widgets as sw
from sprox.sa.widgetselector import SAWidgetSelector
from sprox.sa.validatorselector import SAValidatorSelector, Email
from sauce.widgets.widgets import (LargeMixin, SmallMixin, AdvancedWysihtml5,
MediumTextField, SmallTextField, CalendarDateTimePicker)
from sauce.widgets.validators import AdvancedWysihtml5BleachValidator
class ChosenPropertyMultipleSelectField(LargeMixin, twjc.ChosenMultipleSelectField, sw.PropertyMultipleSelectField):
search_contains = True
def | (self, value, state=None):
value = super(ChosenPropertyMultipleSelectField, self)._validate(value, state)
if self.required and not value:
raise twc.ValidationError('Please select at least one value')
else:
return value
class ChosenPropertySingleSelectField(SmallMixin, twjc.ChosenSingleSelectField, sw.PropertySingleSelectField):
search_contains = True
class MyWidgetSelector(SAWidgetSelector):
'''Custom WidgetSelector for SAUCE
Primarily uses fields from tw2.bootstrap.forms and tw2.jqplugins.chosen.
'''
text_field_limit = 256
default_multiple_select_field_widget_type = ChosenPropertyMultipleSelectField
default_single_select_field_widget_type = ChosenPropertySingleSelectField
default_name_based_widgets = {
'name': MediumTextField,
'subject': MediumTextField,
'_url': MediumTextField,
'user_name': MediumTextField,
'email_address': MediumTextField,
'_display_name': MediumTextField,
'description': AdvancedWysihtml5,
'message': AdvancedWysihtml5,
}
def __init__(self, *args, **kwargs):
self.default_widgets.update({
sqlat.String: MediumTextField,
sqlat.Integer: SmallTextField,
sqlat.Numeric: SmallTextField,
sqlat.DateTime: CalendarDateTimePicker,
sqlat.Date: twb.CalendarDatePicker,
sqlat.Time: twb.CalendarTimePicker,
sqlat.Binary: twb.FileField,
sqlat.BLOB: twb.FileField,
sqlat.PickleType: MediumTextField,
sqlat.Enum: twjc.ChosenSingleSelectField,
})
super(MyWidgetSelector, self).__init__(*args, **kwargs)
def select(self, field):
widget = super(MyWidgetSelector, self).select(field)
if (issubclass(widget, sw.TextArea)
and hasattr(field.type, 'length')
and (field.type.length is None or field.type.length < self.text_field_limit)):
widget = MediumTextField
return widget
class MyValidatorSelector(SAValidatorSelector):
_name_based_validators = {
'email_address': Email,
'description': AdvancedWysihtml5BleachValidator,
'message': AdvancedWysihtml5BleachValidator,
}
# def select(self, field):
# print 'MyValidatorSelector', 'select', field
# return super(MyValidatorSelector, self).select(field)
| _validate | identifier_name |
selectors.py | '''
@since: 2015-01-07
@author: moschlar
'''
import sqlalchemy.types as sqlat
import tw2.core as twc
import tw2.bootstrap.forms as twb
import tw2.jqplugins.chosen.widgets as twjc
import sprox.widgets.tw2widgets.widgets as sw
from sprox.sa.widgetselector import SAWidgetSelector
from sprox.sa.validatorselector import SAValidatorSelector, Email
from sauce.widgets.widgets import (LargeMixin, SmallMixin, AdvancedWysihtml5,
MediumTextField, SmallTextField, CalendarDateTimePicker)
from sauce.widgets.validators import AdvancedWysihtml5BleachValidator
class ChosenPropertyMultipleSelectField(LargeMixin, twjc.ChosenMultipleSelectField, sw.PropertyMultipleSelectField):
|
class ChosenPropertySingleSelectField(SmallMixin, twjc.ChosenSingleSelectField, sw.PropertySingleSelectField):
search_contains = True
class MyWidgetSelector(SAWidgetSelector):
'''Custom WidgetSelector for SAUCE
Primarily uses fields from tw2.bootstrap.forms and tw2.jqplugins.chosen.
'''
text_field_limit = 256
default_multiple_select_field_widget_type = ChosenPropertyMultipleSelectField
default_single_select_field_widget_type = ChosenPropertySingleSelectField
default_name_based_widgets = {
'name': MediumTextField,
'subject': MediumTextField,
'_url': MediumTextField,
'user_name': MediumTextField,
'email_address': MediumTextField,
'_display_name': MediumTextField,
'description': AdvancedWysihtml5,
'message': AdvancedWysihtml5,
}
def __init__(self, *args, **kwargs):
self.default_widgets.update({
sqlat.String: MediumTextField,
sqlat.Integer: SmallTextField,
sqlat.Numeric: SmallTextField,
sqlat.DateTime: CalendarDateTimePicker,
sqlat.Date: twb.CalendarDatePicker,
sqlat.Time: twb.CalendarTimePicker,
sqlat.Binary: twb.FileField,
sqlat.BLOB: twb.FileField,
sqlat.PickleType: MediumTextField,
sqlat.Enum: twjc.ChosenSingleSelectField,
})
super(MyWidgetSelector, self).__init__(*args, **kwargs)
def select(self, field):
widget = super(MyWidgetSelector, self).select(field)
if (issubclass(widget, sw.TextArea)
and hasattr(field.type, 'length')
and (field.type.length is None or field.type.length < self.text_field_limit)):
widget = MediumTextField
return widget
class MyValidatorSelector(SAValidatorSelector):
_name_based_validators = {
'email_address': Email,
'description': AdvancedWysihtml5BleachValidator,
'message': AdvancedWysihtml5BleachValidator,
}
# def select(self, field):
# print 'MyValidatorSelector', 'select', field
# return super(MyValidatorSelector, self).select(field)
| search_contains = True
def _validate(self, value, state=None):
value = super(ChosenPropertyMultipleSelectField, self)._validate(value, state)
if self.required and not value:
raise twc.ValidationError('Please select at least one value')
else:
return value | identifier_body |
android_policy_writer_unittest.py | #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for writers.android_policy_writer'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
import unittest
from xml.dom import minidom
from writers import writer_unittest_common
from writers import android_policy_writer
class AndroidPolicyWriterUnittest(writer_unittest_common.WriterUnittestCommon):
'''Unit tests to test assumptions in Android Policy Writer'''
def testPolicyWithoutItems(self):
# Test an example policy without items.
policy = {
'name': '_policy_name',
'caption': '_policy_caption',
'desc': 'This is a long policy caption. More than one sentence '
'in a single line because it is very important.\n'
'Second line, also important'
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">This is a long policy caption. More '
'than one sentence in a single line because it is very '
'important.\nSecond line, also important'
'</string>'
'</resources>')
def testPolicyWithItems(self):
# Test an example policy without items.
|
if __name__ == '__main__':
unittest.main()
| policy = {
'name':
'_policy_name',
'caption':
'_policy_caption',
'desc':
'_policy_desc_first.\nadditional line',
'items': [{
'caption': '_caption1',
'value': '_value1',
}, {
'caption': '_caption2',
'value': '_value2',
},
{
'caption': '_caption3',
'value': '_value3',
'supported_on': [{
'platform': 'win'
}, {
'platform': 'win7'
}]
},
{
'caption':
'_caption4',
'value':
'_value4',
'supported_on': [{
'platform': 'android'
}, {
'platform': 'win7'
}]
}]
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">_policy_desc_first.\n'
'additional line</string>'
'<string-array name="_policy_nameEntries">'
'<item>_caption1</item>'
'<item>_caption2</item>'
'<item>_caption4</item>'
'</string-array>'
'<string-array name="_policy_nameValues">'
'<item>_value1</item>'
'<item>_value2</item>'
'<item>_value4</item>'
'</string-array>'
'</resources>') | identifier_body |
android_policy_writer_unittest.py | #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for writers.android_policy_writer'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
import unittest
from xml.dom import minidom
from writers import writer_unittest_common
from writers import android_policy_writer
class AndroidPolicyWriterUnittest(writer_unittest_common.WriterUnittestCommon):
'''Unit tests to test assumptions in Android Policy Writer'''
def testPolicyWithoutItems(self):
# Test an example policy without items.
policy = {
'name': '_policy_name',
'caption': '_policy_caption',
'desc': 'This is a long policy caption. More than one sentence '
'in a single line because it is very important.\n'
'Second line, also important'
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">This is a long policy caption. More '
'than one sentence in a single line because it is very '
'important.\nSecond line, also important'
'</string>'
'</resources>')
def | (self):
# Test an example policy without items.
policy = {
'name':
'_policy_name',
'caption':
'_policy_caption',
'desc':
'_policy_desc_first.\nadditional line',
'items': [{
'caption': '_caption1',
'value': '_value1',
}, {
'caption': '_caption2',
'value': '_value2',
},
{
'caption': '_caption3',
'value': '_value3',
'supported_on': [{
'platform': 'win'
}, {
'platform': 'win7'
}]
},
{
'caption':
'_caption4',
'value':
'_value4',
'supported_on': [{
'platform': 'android'
}, {
'platform': 'win7'
}]
}]
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">_policy_desc_first.\n'
'additional line</string>'
'<string-array name="_policy_nameEntries">'
'<item>_caption1</item>'
'<item>_caption2</item>'
'<item>_caption4</item>'
'</string-array>'
'<string-array name="_policy_nameValues">'
'<item>_value1</item>'
'<item>_value2</item>'
'<item>_value4</item>'
'</string-array>'
'</resources>')
if __name__ == '__main__':
unittest.main()
| testPolicyWithItems | identifier_name |
android_policy_writer_unittest.py | #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for writers.android_policy_writer'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
import unittest
from xml.dom import minidom
from writers import writer_unittest_common
from writers import android_policy_writer
class AndroidPolicyWriterUnittest(writer_unittest_common.WriterUnittestCommon):
'''Unit tests to test assumptions in Android Policy Writer'''
def testPolicyWithoutItems(self):
# Test an example policy without items.
policy = {
'name': '_policy_name',
'caption': '_policy_caption',
'desc': 'This is a long policy caption. More than one sentence '
'in a single line because it is very important.\n'
'Second line, also important'
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">This is a long policy caption. More '
'than one sentence in a single line because it is very '
'important.\nSecond line, also important'
'</string>'
'</resources>')
def testPolicyWithItems(self):
# Test an example policy without items.
policy = {
'name':
'_policy_name',
'caption':
'_policy_caption',
'desc':
'_policy_desc_first.\nadditional line',
'items': [{
'caption': '_caption1', | }, {
'caption': '_caption2',
'value': '_value2',
},
{
'caption': '_caption3',
'value': '_value3',
'supported_on': [{
'platform': 'win'
}, {
'platform': 'win7'
}]
},
{
'caption':
'_caption4',
'value':
'_value4',
'supported_on': [{
'platform': 'android'
}, {
'platform': 'win7'
}]
}]
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">_policy_desc_first.\n'
'additional line</string>'
'<string-array name="_policy_nameEntries">'
'<item>_caption1</item>'
'<item>_caption2</item>'
'<item>_caption4</item>'
'</string-array>'
'<string-array name="_policy_nameValues">'
'<item>_value1</item>'
'<item>_value2</item>'
'<item>_value4</item>'
'</string-array>'
'</resources>')
if __name__ == '__main__':
unittest.main() | 'value': '_value1', | random_line_split |
android_policy_writer_unittest.py | #!/usr/bin/env python
# Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for writers.android_policy_writer'''
import os
import sys
if __name__ == '__main__':
|
import unittest
from xml.dom import minidom
from writers import writer_unittest_common
from writers import android_policy_writer
class AndroidPolicyWriterUnittest(writer_unittest_common.WriterUnittestCommon):
'''Unit tests to test assumptions in Android Policy Writer'''
def testPolicyWithoutItems(self):
# Test an example policy without items.
policy = {
'name': '_policy_name',
'caption': '_policy_caption',
'desc': 'This is a long policy caption. More than one sentence '
'in a single line because it is very important.\n'
'Second line, also important'
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">This is a long policy caption. More '
'than one sentence in a single line because it is very '
'important.\nSecond line, also important'
'</string>'
'</resources>')
def testPolicyWithItems(self):
# Test an example policy without items.
policy = {
'name':
'_policy_name',
'caption':
'_policy_caption',
'desc':
'_policy_desc_first.\nadditional line',
'items': [{
'caption': '_caption1',
'value': '_value1',
}, {
'caption': '_caption2',
'value': '_value2',
},
{
'caption': '_caption3',
'value': '_value3',
'supported_on': [{
'platform': 'win'
}, {
'platform': 'win7'
}]
},
{
'caption':
'_caption4',
'value':
'_value4',
'supported_on': [{
'platform': 'android'
}, {
'platform': 'win7'
}]
}]
}
writer = android_policy_writer.GetWriter({})
writer.Init()
writer.BeginTemplate()
writer.WritePolicy(policy)
self.assertEquals(
writer._resources.toxml(), '<resources>'
'<string name="_policy_nameTitle">_policy_caption</string>'
'<string name="_policy_nameDesc">_policy_desc_first.\n'
'additional line</string>'
'<string-array name="_policy_nameEntries">'
'<item>_caption1</item>'
'<item>_caption2</item>'
'<item>_caption4</item>'
'</string-array>'
'<string-array name="_policy_nameValues">'
'<item>_value1</item>'
'<item>_value2</item>'
'<item>_value4</item>'
'</string-array>'
'</resources>')
if __name__ == '__main__':
unittest.main()
| sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..')) | conditional_block |
connector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::hosts::replace_host;
use crate::http_loader::Decoder;
use flate2::read::GzDecoder;
use hyper::body::Payload;
use hyper::client::connect::{Connect, Destination};
use hyper::client::HttpConnector as HyperHttpConnector;
use hyper::rt::Future;
use hyper::{Body, Client};
use hyper_openssl::HttpsConnector;
use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions};
use openssl::x509;
use std::io::{Cursor, Read};
use tokio::prelude::future::Executor;
use tokio::prelude::{Async, Stream};
pub const BUF_SIZE: usize = 32768;
pub struct HttpConnector {
inner: HyperHttpConnector,
}
impl HttpConnector {
fn new() -> HttpConnector {
let mut inner = HyperHttpConnector::new(4);
inner.enforce_http(false);
inner.set_happy_eyeballs_timeout(None);
HttpConnector { inner }
}
}
impl Connect for HttpConnector {
type Transport = <HyperHttpConnector as Connect>::Transport;
type Error = <HyperHttpConnector as Connect>::Error;
type Future = <HyperHttpConnector as Connect>::Future;
fn connect(&self, dest: Destination) -> Self::Future {
// Perform host replacement when making the actual TCP connection.
let mut new_dest = dest.clone();
let addr = replace_host(dest.host());
new_dest.set_host(&*addr).unwrap();
self.inner.connect(new_dest)
}
}
pub type Connector = HttpsConnector<HttpConnector>;
pub struct WrappedBody {
pub body: Body,
pub decoder: Decoder,
}
impl WrappedBody {
pub fn new(body: Body) -> Self {
Self::new_with_decoder(body, Decoder::Plain)
}
pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self {
WrappedBody { body, decoder }
}
}
impl Payload for WrappedBody {
type Data = <Body as Payload>::Data;
type Error = <Body as Payload>::Error;
fn poll_data(&mut self) -> Result<Async<Option<Self::Data>>, Self::Error> {
self.body.poll_data()
}
}
impl Stream for WrappedBody {
type Item = <Body as Stream>::Item;
type Error = <Body as Stream>::Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
self.body.poll().map(|res| {
res.map(|maybe_chunk| {
if let Some(chunk) = maybe_chunk | else {
// Hyper is done downloading but we still have uncompressed data
match self.decoder {
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
_ => None,
}
}
})
})
}
}
pub fn create_ssl_connector_builder(certs: &str) -> SslConnectorBuilder {
// certs include multiple certificates. We could add all of them at once,
// but if any of them were already added, openssl would fail to insert all
// of them.
let mut certs = certs;
let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
loop {
let token = "-----END CERTIFICATE-----";
if let Some(index) = certs.find(token) {
let (cert, rest) = certs.split_at(index + token.len());
certs = rest;
let cert = x509::X509::from_pem(cert.as_bytes()).unwrap();
ssl_connector_builder
.cert_store_mut()
.add_cert(cert)
.or_else(|e| {
let v: Option<Option<&str>> = e.errors().iter().nth(0).map(|e| e.reason());
if v == Some(Some("cert already in hash table")) {
warn!("Cert already in hash table. Ignoring.");
// Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
// certificate is already in the store.
Ok(())
} else {
Err(e)
}
})
.expect("could not set CA file");
} else {
break;
}
}
ssl_connector_builder
.set_cipher_list(DEFAULT_CIPHERS)
.expect("could not set ciphers");
ssl_connector_builder
.set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION);
ssl_connector_builder
}
pub fn create_http_client<E>(
ssl_connector_builder: SslConnectorBuilder,
executor: E,
) -> Client<Connector, WrappedBody>
where
E: Executor<Box<dyn Future<Error = (), Item = ()> + Send + 'static>> + Sync + Send + 'static,
{
let connector =
HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap();
Client::builder()
.http1_title_case_headers(true)
.executor(executor)
.build(connector)
}
// The basic logic here is to prefer ciphers with ECDSA certificates, Forward
// Secrecy, AES GCM ciphers, AES ciphers, and finally 3DES ciphers.
// A complete discussion of the issues involved in TLS configuration can be found here:
// https://wiki.mozilla.org/Security/Server_Side_TLS
const DEFAULT_CIPHERS: &'static str = concat!(
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:",
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:",
"DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:",
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:",
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:",
"ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:",
"DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:",
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:",
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA"
);
| {
match self.decoder {
Decoder::Plain => Some(chunk),
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Gzip(None) => {
let mut buf = vec![0; BUF_SIZE];
let mut decoder = GzDecoder::new(Cursor::new(chunk.into_bytes()));
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
self.decoder = Decoder::Gzip(Some(decoder));
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
}
} | conditional_block |
connector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::hosts::replace_host;
use crate::http_loader::Decoder;
use flate2::read::GzDecoder;
use hyper::body::Payload;
use hyper::client::connect::{Connect, Destination};
use hyper::client::HttpConnector as HyperHttpConnector;
use hyper::rt::Future;
use hyper::{Body, Client};
use hyper_openssl::HttpsConnector;
use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions};
use openssl::x509;
use std::io::{Cursor, Read};
use tokio::prelude::future::Executor;
use tokio::prelude::{Async, Stream};
pub const BUF_SIZE: usize = 32768;
pub struct HttpConnector {
inner: HyperHttpConnector,
}
impl HttpConnector {
fn new() -> HttpConnector {
let mut inner = HyperHttpConnector::new(4);
inner.enforce_http(false);
inner.set_happy_eyeballs_timeout(None);
HttpConnector { inner }
}
}
impl Connect for HttpConnector {
type Transport = <HyperHttpConnector as Connect>::Transport;
type Error = <HyperHttpConnector as Connect>::Error;
type Future = <HyperHttpConnector as Connect>::Future;
fn connect(&self, dest: Destination) -> Self::Future {
// Perform host replacement when making the actual TCP connection.
let mut new_dest = dest.clone();
let addr = replace_host(dest.host());
new_dest.set_host(&*addr).unwrap();
self.inner.connect(new_dest)
}
}
pub type Connector = HttpsConnector<HttpConnector>;
pub struct WrappedBody {
pub body: Body,
pub decoder: Decoder,
}
impl WrappedBody {
pub fn new(body: Body) -> Self {
Self::new_with_decoder(body, Decoder::Plain)
}
pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self {
WrappedBody { body, decoder }
}
}
impl Payload for WrappedBody {
type Data = <Body as Payload>::Data;
type Error = <Body as Payload>::Error;
fn poll_data(&mut self) -> Result<Async<Option<Self::Data>>, Self::Error> {
self.body.poll_data()
}
}
impl Stream for WrappedBody {
type Item = <Body as Stream>::Item;
type Error = <Body as Stream>::Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
self.body.poll().map(|res| {
res.map(|maybe_chunk| {
if let Some(chunk) = maybe_chunk {
match self.decoder {
Decoder::Plain => Some(chunk),
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Gzip(None) => {
let mut buf = vec![0; BUF_SIZE];
let mut decoder = GzDecoder::new(Cursor::new(chunk.into_bytes()));
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
self.decoder = Decoder::Gzip(Some(decoder));
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
}
} else {
// Hyper is done downloading but we still have uncompressed data
match self.decoder {
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
_ => None,
}
}
})
})
}
}
pub fn create_ssl_connector_builder(certs: &str) -> SslConnectorBuilder {
// certs include multiple certificates. We could add all of them at once,
// but if any of them were already added, openssl would fail to insert all
// of them.
let mut certs = certs;
let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap(); | let cert = x509::X509::from_pem(cert.as_bytes()).unwrap();
ssl_connector_builder
.cert_store_mut()
.add_cert(cert)
.or_else(|e| {
let v: Option<Option<&str>> = e.errors().iter().nth(0).map(|e| e.reason());
if v == Some(Some("cert already in hash table")) {
warn!("Cert already in hash table. Ignoring.");
// Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
// certificate is already in the store.
Ok(())
} else {
Err(e)
}
})
.expect("could not set CA file");
} else {
break;
}
}
ssl_connector_builder
.set_cipher_list(DEFAULT_CIPHERS)
.expect("could not set ciphers");
ssl_connector_builder
.set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION);
ssl_connector_builder
}
pub fn create_http_client<E>(
ssl_connector_builder: SslConnectorBuilder,
executor: E,
) -> Client<Connector, WrappedBody>
where
E: Executor<Box<dyn Future<Error = (), Item = ()> + Send + 'static>> + Sync + Send + 'static,
{
let connector =
HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap();
Client::builder()
.http1_title_case_headers(true)
.executor(executor)
.build(connector)
}
// The basic logic here is to prefer ciphers with ECDSA certificates, Forward
// Secrecy, AES GCM ciphers, AES ciphers, and finally 3DES ciphers.
// A complete discussion of the issues involved in TLS configuration can be found here:
// https://wiki.mozilla.org/Security/Server_Side_TLS
const DEFAULT_CIPHERS: &'static str = concat!(
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:",
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:",
"DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:",
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:",
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:",
"ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:",
"DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:",
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:",
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA"
); | loop {
let token = "-----END CERTIFICATE-----";
if let Some(index) = certs.find(token) {
let (cert, rest) = certs.split_at(index + token.len());
certs = rest; | random_line_split |
connector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::hosts::replace_host;
use crate::http_loader::Decoder;
use flate2::read::GzDecoder;
use hyper::body::Payload;
use hyper::client::connect::{Connect, Destination};
use hyper::client::HttpConnector as HyperHttpConnector;
use hyper::rt::Future;
use hyper::{Body, Client};
use hyper_openssl::HttpsConnector;
use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions};
use openssl::x509;
use std::io::{Cursor, Read};
use tokio::prelude::future::Executor;
use tokio::prelude::{Async, Stream};
pub const BUF_SIZE: usize = 32768;
pub struct HttpConnector {
inner: HyperHttpConnector,
}
impl HttpConnector {
fn new() -> HttpConnector {
let mut inner = HyperHttpConnector::new(4);
inner.enforce_http(false);
inner.set_happy_eyeballs_timeout(None);
HttpConnector { inner }
}
}
impl Connect for HttpConnector {
type Transport = <HyperHttpConnector as Connect>::Transport;
type Error = <HyperHttpConnector as Connect>::Error;
type Future = <HyperHttpConnector as Connect>::Future;
fn connect(&self, dest: Destination) -> Self::Future {
// Perform host replacement when making the actual TCP connection.
let mut new_dest = dest.clone();
let addr = replace_host(dest.host());
new_dest.set_host(&*addr).unwrap();
self.inner.connect(new_dest)
}
}
pub type Connector = HttpsConnector<HttpConnector>;
pub struct WrappedBody {
pub body: Body,
pub decoder: Decoder,
}
impl WrappedBody {
pub fn new(body: Body) -> Self {
Self::new_with_decoder(body, Decoder::Plain)
}
pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self {
WrappedBody { body, decoder }
}
}
impl Payload for WrappedBody {
type Data = <Body as Payload>::Data;
type Error = <Body as Payload>::Error;
fn | (&mut self) -> Result<Async<Option<Self::Data>>, Self::Error> {
self.body.poll_data()
}
}
impl Stream for WrappedBody {
type Item = <Body as Stream>::Item;
type Error = <Body as Stream>::Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
self.body.poll().map(|res| {
res.map(|maybe_chunk| {
if let Some(chunk) = maybe_chunk {
match self.decoder {
Decoder::Plain => Some(chunk),
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Gzip(None) => {
let mut buf = vec![0; BUF_SIZE];
let mut decoder = GzDecoder::new(Cursor::new(chunk.into_bytes()));
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
self.decoder = Decoder::Gzip(Some(decoder));
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
}
} else {
// Hyper is done downloading but we still have uncompressed data
match self.decoder {
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
_ => None,
}
}
})
})
}
}
pub fn create_ssl_connector_builder(certs: &str) -> SslConnectorBuilder {
// certs include multiple certificates. We could add all of them at once,
// but if any of them were already added, openssl would fail to insert all
// of them.
let mut certs = certs;
let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
loop {
let token = "-----END CERTIFICATE-----";
if let Some(index) = certs.find(token) {
let (cert, rest) = certs.split_at(index + token.len());
certs = rest;
let cert = x509::X509::from_pem(cert.as_bytes()).unwrap();
ssl_connector_builder
.cert_store_mut()
.add_cert(cert)
.or_else(|e| {
let v: Option<Option<&str>> = e.errors().iter().nth(0).map(|e| e.reason());
if v == Some(Some("cert already in hash table")) {
warn!("Cert already in hash table. Ignoring.");
// Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
// certificate is already in the store.
Ok(())
} else {
Err(e)
}
})
.expect("could not set CA file");
} else {
break;
}
}
ssl_connector_builder
.set_cipher_list(DEFAULT_CIPHERS)
.expect("could not set ciphers");
ssl_connector_builder
.set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION);
ssl_connector_builder
}
pub fn create_http_client<E>(
ssl_connector_builder: SslConnectorBuilder,
executor: E,
) -> Client<Connector, WrappedBody>
where
E: Executor<Box<dyn Future<Error = (), Item = ()> + Send + 'static>> + Sync + Send + 'static,
{
let connector =
HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap();
Client::builder()
.http1_title_case_headers(true)
.executor(executor)
.build(connector)
}
// The basic logic here is to prefer ciphers with ECDSA certificates, Forward
// Secrecy, AES GCM ciphers, AES ciphers, and finally 3DES ciphers.
// A complete discussion of the issues involved in TLS configuration can be found here:
// https://wiki.mozilla.org/Security/Server_Side_TLS
const DEFAULT_CIPHERS: &'static str = concat!(
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:",
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:",
"DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:",
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:",
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:",
"ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:",
"DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:",
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:",
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA"
);
| poll_data | identifier_name |
connector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::hosts::replace_host;
use crate::http_loader::Decoder;
use flate2::read::GzDecoder;
use hyper::body::Payload;
use hyper::client::connect::{Connect, Destination};
use hyper::client::HttpConnector as HyperHttpConnector;
use hyper::rt::Future;
use hyper::{Body, Client};
use hyper_openssl::HttpsConnector;
use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions};
use openssl::x509;
use std::io::{Cursor, Read};
use tokio::prelude::future::Executor;
use tokio::prelude::{Async, Stream};
pub const BUF_SIZE: usize = 32768;
pub struct HttpConnector {
inner: HyperHttpConnector,
}
impl HttpConnector {
fn new() -> HttpConnector {
let mut inner = HyperHttpConnector::new(4);
inner.enforce_http(false);
inner.set_happy_eyeballs_timeout(None);
HttpConnector { inner }
}
}
impl Connect for HttpConnector {
type Transport = <HyperHttpConnector as Connect>::Transport;
type Error = <HyperHttpConnector as Connect>::Error;
type Future = <HyperHttpConnector as Connect>::Future;
fn connect(&self, dest: Destination) -> Self::Future |
}
pub type Connector = HttpsConnector<HttpConnector>;
pub struct WrappedBody {
pub body: Body,
pub decoder: Decoder,
}
impl WrappedBody {
pub fn new(body: Body) -> Self {
Self::new_with_decoder(body, Decoder::Plain)
}
pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self {
WrappedBody { body, decoder }
}
}
impl Payload for WrappedBody {
type Data = <Body as Payload>::Data;
type Error = <Body as Payload>::Error;
fn poll_data(&mut self) -> Result<Async<Option<Self::Data>>, Self::Error> {
self.body.poll_data()
}
}
impl Stream for WrappedBody {
type Item = <Body as Stream>::Item;
type Error = <Body as Stream>::Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
self.body.poll().map(|res| {
res.map(|maybe_chunk| {
if let Some(chunk) = maybe_chunk {
match self.decoder {
Decoder::Plain => Some(chunk),
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Gzip(None) => {
let mut buf = vec![0; BUF_SIZE];
let mut decoder = GzDecoder::new(Cursor::new(chunk.into_bytes()));
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
self.decoder = Decoder::Gzip(Some(decoder));
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
decoder.get_mut().get_mut().extend(chunk.as_ref());
let len = decoder.read(&mut buf).ok()?;
buf.truncate(len);
Some(buf.into())
},
}
} else {
// Hyper is done downloading but we still have uncompressed data
match self.decoder {
Decoder::Gzip(Some(ref mut decoder)) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Deflate(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
Decoder::Brotli(ref mut decoder) => {
let mut buf = vec![0; BUF_SIZE];
let len = decoder.read(&mut buf).ok()?;
if len == 0 {
return None;
}
buf.truncate(len);
Some(buf.into())
},
_ => None,
}
}
})
})
}
}
pub fn create_ssl_connector_builder(certs: &str) -> SslConnectorBuilder {
// certs include multiple certificates. We could add all of them at once,
// but if any of them were already added, openssl would fail to insert all
// of them.
let mut certs = certs;
let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
loop {
let token = "-----END CERTIFICATE-----";
if let Some(index) = certs.find(token) {
let (cert, rest) = certs.split_at(index + token.len());
certs = rest;
let cert = x509::X509::from_pem(cert.as_bytes()).unwrap();
ssl_connector_builder
.cert_store_mut()
.add_cert(cert)
.or_else(|e| {
let v: Option<Option<&str>> = e.errors().iter().nth(0).map(|e| e.reason());
if v == Some(Some("cert already in hash table")) {
warn!("Cert already in hash table. Ignoring.");
// Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
// certificate is already in the store.
Ok(())
} else {
Err(e)
}
})
.expect("could not set CA file");
} else {
break;
}
}
ssl_connector_builder
.set_cipher_list(DEFAULT_CIPHERS)
.expect("could not set ciphers");
ssl_connector_builder
.set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION);
ssl_connector_builder
}
pub fn create_http_client<E>(
ssl_connector_builder: SslConnectorBuilder,
executor: E,
) -> Client<Connector, WrappedBody>
where
E: Executor<Box<dyn Future<Error = (), Item = ()> + Send + 'static>> + Sync + Send + 'static,
{
let connector =
HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap();
Client::builder()
.http1_title_case_headers(true)
.executor(executor)
.build(connector)
}
// The basic logic here is to prefer ciphers with ECDSA certificates, Forward
// Secrecy, AES GCM ciphers, AES ciphers, and finally 3DES ciphers.
// A complete discussion of the issues involved in TLS configuration can be found here:
// https://wiki.mozilla.org/Security/Server_Side_TLS
const DEFAULT_CIPHERS: &'static str = concat!(
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:",
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:",
"DHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:",
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:",
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:",
"ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:",
"DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:",
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:",
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA"
);
| {
// Perform host replacement when making the actual TCP connection.
let mut new_dest = dest.clone();
let addr = replace_host(dest.host());
new_dest.set_host(&*addr).unwrap();
self.inner.connect(new_dest)
} | identifier_body |
jwc-service.ts | import {Injectable} from '@angular/core';
import {Api} from './api';
import 'rxjs/Rx';
import {Headers, RequestOptions} from '@angular/http';
import {Holder} from './holder';
@Injectable()
export class | {
private headers: Headers = new Headers();
private requestOption: RequestOptions = new RequestOptions({headers: this.headers, withCredentials: true});
constructor(private api: Api, private holder: Holder) {
}
calScore(payload: { zjh: string, mm: string, date: Date }) {
let seq = this.api.post('service/jwc/score', payload, this.requestOption).share();//发包
seq.subscribe(() => {
}, err => {
console.error('ERROR', err);
this.holder.alerts.push({level: 'alert-danger', content: '服务器故障,请稍后再试'});
});
return seq;
}
getScoreResult(payload: { zjh: string, mm: string, date: Date }) {
let seq = this.api.post('service/jwc/score/result', payload, this.requestOption).share();
seq.subscribe(() => {
}, err => {
console.error('ERROR', err);
this.holder.alerts.push({level: 'alert-danger', content: '服务器故障,请稍后再试'});
});
return seq;
}
}
| JWCService | identifier_name |
jwc-service.ts | import {Injectable} from '@angular/core';
import {Api} from './api';
import 'rxjs/Rx';
import {Headers, RequestOptions} from '@angular/http';
import {Holder} from './holder';
@Injectable()
export class JWCService {
private headers: Headers = new Headers();
private requestOption: RequestOptions = new RequestOptions({headers: this.headers, withCredentials: true});
constructor(private api: Api, private holder: Holder) {
}
calScore(payload: { zjh: string, mm: string, date: Date }) {
let seq = this.api.post('service/jwc/score', payload, this.requestOption).share();//发包
seq.subscribe(() => {
}, err => {
console.error('ERROR', err);
this.holder.alerts.push({level: 'alert-danger', content: '服务器故障,请稍后再试'});
});
return seq;
}
getScoreResult(payload: { zjh: string, mm: string, date: Date }) {
let seq = this.api.post('service/jwc/score/result', payload, this.requestOption).share();
seq.subscribe(() => {
}, err => {
console.error('ERROR', err);
this.holder.alerts.push({level: 'alert-danger', content: '服务器故障,请稍后再试'});
});
return seq; | }
} | random_line_split | |
jwc-service.ts | import {Injectable} from '@angular/core';
import {Api} from './api';
import 'rxjs/Rx';
import {Headers, RequestOptions} from '@angular/http';
import {Holder} from './holder';
@Injectable()
export class JWCService {
private headers: Headers = new Headers();
private requestOption: RequestOptions = new RequestOptions({headers: this.headers, withCredentials: true});
constructor(private api: Api, private holder: Holder) |
calScore(payload: { zjh: string, mm: string, date: Date }) {
let seq = this.api.post('service/jwc/score', payload, this.requestOption).share();//发包
seq.subscribe(() => {
}, err => {
console.error('ERROR', err);
this.holder.alerts.push({level: 'alert-danger', content: '服务器故障,请稍后再试'});
});
return seq;
}
getScoreResult(payload: { zjh: string, mm: string, date: Date }) {
let seq = this.api.post('service/jwc/score/result', payload, this.requestOption).share();
seq.subscribe(() => {
}, err => {
console.error('ERROR', err);
this.holder.alerts.push({level: 'alert-danger', content: '服务器故障,请稍后再试'});
});
return seq;
}
}
| {
} | identifier_body |
ds_tc_resnet_test.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for ds_tc_resnet model in session mode."""
import numpy as np
from kws_streaming.layers import test_utils
from kws_streaming.layers.compat import tf
from kws_streaming.layers.compat import tf1
from kws_streaming.layers.modes import Modes
from kws_streaming.models import utils
import kws_streaming.models.ds_tc_resnet as ds_tc_resnet
from kws_streaming.train import inference
class DsTcResnetTest(tf.test.TestCase):
"""Test ds_tc_resnet model in non streaming and streaming modes."""
def setUp(self):
super(DsTcResnetTest, self).setUp()
config = tf1.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf1.Session(config=config)
tf1.keras.backend.set_session(self.sess)
tf.keras.backend.set_learning_phase(0)
test_utils.set_seed(123)
self.params = utils.ds_tc_resnet_model_params(True)
self.model = ds_tc_resnet.model(self.params)
self.model.summary()
self.input_data = np.random.rand(self.params.batch_size,
self.params.desired_samples)
# run non streaming inference
self.non_stream_out = self.model.predict(self.input_data)
def test_ds_tc_resnet_stream(self):
"""Test for tf streaming with internal state."""
# prepare tf streaming model
model_stream = utils.to_streaming_inference(
self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE)
model_stream.summary()
# run streaming inference
stream_out = inference.run_stream_inference_classification(
self.params, model_stream, self.input_data)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
def test_ds_tc_resnet_stream_tflite(self):
"""Test for tflite streaming with external state."""
tflite_streaming_model = utils.model_to_tflite(
self.sess, self.model, self.params,
Modes.STREAM_EXTERNAL_STATE_INFERENCE)
interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model) | # before processing new test sequence we reset model state
inputs = []
for detail in interpreter.get_input_details():
inputs.append(np.zeros(detail['shape'], dtype=np.float32))
stream_out = inference.run_stream_inference_classification_tflite(
self.params, interpreter, self.input_data, inputs)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
if __name__ == '__main__':
tf1.disable_eager_execution()
tf.test.main() | interpreter.allocate_tensors()
| random_line_split |
ds_tc_resnet_test.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for ds_tc_resnet model in session mode."""
import numpy as np
from kws_streaming.layers import test_utils
from kws_streaming.layers.compat import tf
from kws_streaming.layers.compat import tf1
from kws_streaming.layers.modes import Modes
from kws_streaming.models import utils
import kws_streaming.models.ds_tc_resnet as ds_tc_resnet
from kws_streaming.train import inference
class DsTcResnetTest(tf.test.TestCase):
"""Test ds_tc_resnet model in non streaming and streaming modes."""
def setUp(self):
super(DsTcResnetTest, self).setUp()
config = tf1.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf1.Session(config=config)
tf1.keras.backend.set_session(self.sess)
tf.keras.backend.set_learning_phase(0)
test_utils.set_seed(123)
self.params = utils.ds_tc_resnet_model_params(True)
self.model = ds_tc_resnet.model(self.params)
self.model.summary()
self.input_data = np.random.rand(self.params.batch_size,
self.params.desired_samples)
# run non streaming inference
self.non_stream_out = self.model.predict(self.input_data)
def test_ds_tc_resnet_stream(self):
"""Test for tf streaming with internal state."""
# prepare tf streaming model
model_stream = utils.to_streaming_inference(
self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE)
model_stream.summary()
# run streaming inference
stream_out = inference.run_stream_inference_classification(
self.params, model_stream, self.input_data)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
def test_ds_tc_resnet_stream_tflite(self):
|
if __name__ == '__main__':
tf1.disable_eager_execution()
tf.test.main()
| """Test for tflite streaming with external state."""
tflite_streaming_model = utils.model_to_tflite(
self.sess, self.model, self.params,
Modes.STREAM_EXTERNAL_STATE_INFERENCE)
interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model)
interpreter.allocate_tensors()
# before processing new test sequence we reset model state
inputs = []
for detail in interpreter.get_input_details():
inputs.append(np.zeros(detail['shape'], dtype=np.float32))
stream_out = inference.run_stream_inference_classification_tflite(
self.params, interpreter, self.input_data, inputs)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5) | identifier_body |
ds_tc_resnet_test.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for ds_tc_resnet model in session mode."""
import numpy as np
from kws_streaming.layers import test_utils
from kws_streaming.layers.compat import tf
from kws_streaming.layers.compat import tf1
from kws_streaming.layers.modes import Modes
from kws_streaming.models import utils
import kws_streaming.models.ds_tc_resnet as ds_tc_resnet
from kws_streaming.train import inference
class DsTcResnetTest(tf.test.TestCase):
"""Test ds_tc_resnet model in non streaming and streaming modes."""
def setUp(self):
super(DsTcResnetTest, self).setUp()
config = tf1.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf1.Session(config=config)
tf1.keras.backend.set_session(self.sess)
tf.keras.backend.set_learning_phase(0)
test_utils.set_seed(123)
self.params = utils.ds_tc_resnet_model_params(True)
self.model = ds_tc_resnet.model(self.params)
self.model.summary()
self.input_data = np.random.rand(self.params.batch_size,
self.params.desired_samples)
# run non streaming inference
self.non_stream_out = self.model.predict(self.input_data)
def test_ds_tc_resnet_stream(self):
"""Test for tf streaming with internal state."""
# prepare tf streaming model
model_stream = utils.to_streaming_inference(
self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE)
model_stream.summary()
# run streaming inference
stream_out = inference.run_stream_inference_classification(
self.params, model_stream, self.input_data)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
def test_ds_tc_resnet_stream_tflite(self):
"""Test for tflite streaming with external state."""
tflite_streaming_model = utils.model_to_tflite(
self.sess, self.model, self.params,
Modes.STREAM_EXTERNAL_STATE_INFERENCE)
interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model)
interpreter.allocate_tensors()
# before processing new test sequence we reset model state
inputs = []
for detail in interpreter.get_input_details():
inputs.append(np.zeros(detail['shape'], dtype=np.float32))
stream_out = inference.run_stream_inference_classification_tflite(
self.params, interpreter, self.input_data, inputs)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
if __name__ == '__main__':
| tf1.disable_eager_execution()
tf.test.main() | conditional_block | |
ds_tc_resnet_test.py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Test for ds_tc_resnet model in session mode."""
import numpy as np
from kws_streaming.layers import test_utils
from kws_streaming.layers.compat import tf
from kws_streaming.layers.compat import tf1
from kws_streaming.layers.modes import Modes
from kws_streaming.models import utils
import kws_streaming.models.ds_tc_resnet as ds_tc_resnet
from kws_streaming.train import inference
class DsTcResnetTest(tf.test.TestCase):
"""Test ds_tc_resnet model in non streaming and streaming modes."""
def | (self):
super(DsTcResnetTest, self).setUp()
config = tf1.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf1.Session(config=config)
tf1.keras.backend.set_session(self.sess)
tf.keras.backend.set_learning_phase(0)
test_utils.set_seed(123)
self.params = utils.ds_tc_resnet_model_params(True)
self.model = ds_tc_resnet.model(self.params)
self.model.summary()
self.input_data = np.random.rand(self.params.batch_size,
self.params.desired_samples)
# run non streaming inference
self.non_stream_out = self.model.predict(self.input_data)
def test_ds_tc_resnet_stream(self):
"""Test for tf streaming with internal state."""
# prepare tf streaming model
model_stream = utils.to_streaming_inference(
self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE)
model_stream.summary()
# run streaming inference
stream_out = inference.run_stream_inference_classification(
self.params, model_stream, self.input_data)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
def test_ds_tc_resnet_stream_tflite(self):
"""Test for tflite streaming with external state."""
tflite_streaming_model = utils.model_to_tflite(
self.sess, self.model, self.params,
Modes.STREAM_EXTERNAL_STATE_INFERENCE)
interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model)
interpreter.allocate_tensors()
# before processing new test sequence we reset model state
inputs = []
for detail in interpreter.get_input_details():
inputs.append(np.zeros(detail['shape'], dtype=np.float32))
stream_out = inference.run_stream_inference_classification_tflite(
self.params, interpreter, self.input_data, inputs)
self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
if __name__ == '__main__':
tf1.disable_eager_execution()
tf.test.main()
| setUp | identifier_name |
window_test.py | # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gdk
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
|
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self._is_fullscreen())
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self._is_fullscreen())
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def _is_fullscreen(self):
state = self.vimiv["window"].get_window().get_state()
return True if state & Gdk.WindowState.FULLSCREEN else False
@skipUnless(os.getenv("DISPLAY") == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == "__main__":
main()
| cls.init_test(cls, ["vimiv/testimages/"]) | identifier_body |
window_test.py | # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gdk
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def | (cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self._is_fullscreen())
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self._is_fullscreen())
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def _is_fullscreen(self):
state = self.vimiv["window"].get_window().get_state()
return True if state & Gdk.WindowState.FULLSCREEN else False
@skipUnless(os.getenv("DISPLAY") == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == "__main__":
main()
| setUpClass | identifier_name |
window_test.py | # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gdk
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen.""" | refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self._is_fullscreen())
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def _is_fullscreen(self):
state = self.vimiv["window"].get_window().get_state()
return True if state & Gdk.WindowState.FULLSCREEN else False
@skipUnless(os.getenv("DISPLAY") == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == "__main__":
main() | # Start without fullscreen
self.assertFalse(self._is_fullscreen())
# Fullscreen
self.vimiv["window"].toggle_fullscreen() | random_line_split |
window_test.py | # vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gdk
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self._is_fullscreen())
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self._is_fullscreen())
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def _is_fullscreen(self):
state = self.vimiv["window"].get_window().get_state()
return True if state & Gdk.WindowState.FULLSCREEN else False
@skipUnless(os.getenv("DISPLAY") == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == "__main__":
| main() | conditional_block | |
eo.js | /*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'div', 'eo', {
IdInputLabel: 'Id',
advisoryTitleInputLabel: 'Priskriba Titolo',
cssClassInputLabel: 'Stilfolioklasoj',
edit: 'Redakti Div',
inlineStyleInputLabel: 'Enlinia stilo',
langDirLTRLabel: 'Maldekstre dekstren (angle LTR)',
langDirLabel: 'Skribdirekto',
langDirRTLLabel: 'Dekstre maldekstren (angle RTL)',
languageCodeInputLabel: ' Lingvokodo',
remove: 'Forigi Div',
| title: 'Krei DIV ujon',
toolbar: 'Krei DIV ujon'
}); | styleSelectLabel: 'Stilo',
| random_line_split |
scraper.py | '''
Download Cricket Data
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import csv
import sys
import time
import os
import unicodedata
from urlparse import urlparse
from BeautifulSoup import BeautifulSoup, SoupStrainer
BASE_URL = 'http://www.espncricinfo.com'
if not os.path.exists('./espncricinfo-fc'):
|
for i in range(0, 6019):
#odi: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=odi;all=1;page=' + str(i)).read())
#test: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=test;all=1;page=' + str(i)).read())
#t20i: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=t20i;all=1;page=' + str(i)).read())
#t20: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=t20;all=1;page=' + str(i)).read())
#list a: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=list%20a;all=1;page=' + str(i)).read())
#fc:
soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=first%20class;all=1;page=' + str(i)).read())
time.sleep(1)
for new_host in soupy.findAll('a', {'class' : 'srchPlyrNmTxt'}):
try:
new_host = new_host['href']
except:
continue
odiurl = BASE_URL + urlparse(new_host).geturl()
new_host = unicodedata.normalize('NFKD', new_host).encode('ascii','ignore')
print new_host
#print(type(str.split(new_host)[3]))
print str.split(new_host, "/")[4]
html = urllib2.urlopen(odiurl).read()
if html:
with open('espncricinfo-fc/{0!s}'.format(str.split(new_host, "/")[4]), "wb") as f:
f.write(html)
| os.mkdir('./espncricinfo-fc') | conditional_block |
scraper.py | '''
Download Cricket Data
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import csv
import sys
import time
import os
import unicodedata
from urlparse import urlparse
from BeautifulSoup import BeautifulSoup, SoupStrainer
| BASE_URL = 'http://www.espncricinfo.com'
if not os.path.exists('./espncricinfo-fc'):
os.mkdir('./espncricinfo-fc')
for i in range(0, 6019):
#odi: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=odi;all=1;page=' + str(i)).read())
#test: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=test;all=1;page=' + str(i)).read())
#t20i: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=t20i;all=1;page=' + str(i)).read())
#t20: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=t20;all=1;page=' + str(i)).read())
#list a: soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=list%20a;all=1;page=' + str(i)).read())
#fc:
soupy = BeautifulSoup(urllib2.urlopen('http://search.espncricinfo.com/ci/content/match/search.html?search=first%20class;all=1;page=' + str(i)).read())
time.sleep(1)
for new_host in soupy.findAll('a', {'class' : 'srchPlyrNmTxt'}):
try:
new_host = new_host['href']
except:
continue
odiurl = BASE_URL + urlparse(new_host).geturl()
new_host = unicodedata.normalize('NFKD', new_host).encode('ascii','ignore')
print new_host
#print(type(str.split(new_host)[3]))
print str.split(new_host, "/")[4]
html = urllib2.urlopen(odiurl).read()
if html:
with open('espncricinfo-fc/{0!s}'.format(str.split(new_host, "/")[4]), "wb") as f:
f.write(html) | random_line_split | |
__openerp__.py | # -*- coding:utf-8 -*-
#
#
# Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
# All Rights Reserved.
#
# 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/>.
#
# |
{
'name': 'Employee Education Records',
'version': '1.0',
'category': 'Generic Modules/Human Resources',
'description': """
Details About and Employee's Education
======================================
Add an extra field about an employee's education.
""",
'author': "Michael Telahun Makonnen <mmakonnen@gmail.com>,Odoo Community Association (OCA)",
'website': 'http://www.openerp.com',
'license': 'AGPL-3',
'depends': [
'hr',
],
'data': [
'wizard/hr_employee_by_department_view.xml',
'hr_view.xml',
],
'test': [
],
'installable': False,
} | random_line_split | |
test_node.ts | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
// Use the CPU backend for running tests.
import '@tensorflow/tfjs-backend-cpu';
// tslint:disable-next-line:no-imports-from-dist
import * as jasmine_util from '@tensorflow/tfjs-core/dist/jasmine_util';
// tslint:disable-next-line:no-require-imports
const jasmineCtor = require('jasmine');
// tslint:disable-next-line:no-require-imports
Error.stackTraceLimit = Infinity; | throw e;
});
jasmine_util.setTestEnvs(
[{name: 'test-inference-api', backendName: 'cpu', flags: {}}]);
const unitTests = 'src/**/*_test.ts';
const runner = new jasmineCtor();
runner.loadConfig({spec_files: [unitTests], random: false});
runner.execute(); |
process.on('unhandledRejection', e => { | random_line_split |
what_is_going_on.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct UnknownUnits {
pub _address: u8,
}
#[test]
fn bindgen_test_layout_UnknownUnits() {
assert_eq!(
::std::mem::size_of::<UnknownUnits>(),
1usize,
concat!("Size of: ", stringify!(UnknownUnits))
);
assert_eq!(
::std::mem::align_of::<UnknownUnits>(),
1usize, | #[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct PointTyped<F> {
pub x: F,
pub y: F,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<F>>,
}
impl<F> Default for PointTyped<F> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
pub type IntPoint = PointTyped<f32>; | concat!("Alignment of ", stringify!(UnknownUnits))
);
}
pub type Float = f32; | random_line_split |
what_is_going_on.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct UnknownUnits {
pub _address: u8,
}
#[test]
fn bindgen_test_layout_UnknownUnits() |
pub type Float = f32;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct PointTyped<F> {
pub x: F,
pub y: F,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<F>>,
}
impl<F> Default for PointTyped<F> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
pub type IntPoint = PointTyped<f32>;
| {
assert_eq!(
::std::mem::size_of::<UnknownUnits>(),
1usize,
concat!("Size of: ", stringify!(UnknownUnits))
);
assert_eq!(
::std::mem::align_of::<UnknownUnits>(),
1usize,
concat!("Alignment of ", stringify!(UnknownUnits))
);
} | identifier_body |
what_is_going_on.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct UnknownUnits {
pub _address: u8,
}
#[test]
fn bindgen_test_layout_UnknownUnits() {
assert_eq!(
::std::mem::size_of::<UnknownUnits>(),
1usize,
concat!("Size of: ", stringify!(UnknownUnits))
);
assert_eq!(
::std::mem::align_of::<UnknownUnits>(),
1usize,
concat!("Alignment of ", stringify!(UnknownUnits))
);
}
pub type Float = f32;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct | <F> {
pub x: F,
pub y: F,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<F>>,
}
impl<F> Default for PointTyped<F> {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
pub type IntPoint = PointTyped<f32>;
| PointTyped | identifier_name |
networkDrawer.py | import sys
import collections as c
from scipy import special, stats
import numpy as n, pylab as p, networkx as x
class NetworkDrawer:
drawer_count=0
def __init__(self,metric="strength"):
self.drawer_count+=1
metric_=self.standardizeName(metric)
self.metric_=metric_
self.draw_count=0
def standardizeName(self,name):
if name in (["s","strength","st"]+["f","força","forca","fo"]):
name_="s"
if name in (["d","degree","dg"]+["g","grau","gr"]):
name_="d"
return name_
def makeLayout(self,network_measures,network_partitioning=None):
"""Delivers a sequence of user_ids and (x,y) pos.
"""
self.network_measures=network_measures
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degrees
else:
print("not known metric to make layout")
self.ordered_measures=ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
self.measures=measures=list(ordered_measures.values())
self.authors=authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
self.k1=k1=round(total*.80)
self.k2=k2=round(total*.95)
self.periphery=authors[:k1]
self.intermediary=authors[k1:k2]
self.hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
self.k1=k1=len(sectors[0])
self.k2=k2=k1+len(sectors[1])
self.periphery,self.intermediary,self.hubs=sectors
print("fractions ={:0.4f}, {:0.4f}, {:0.4f}".format(k1/total, (k2-k1)/total, 1-k2/total))
self.makeXY()
def drawNetwork(self, network,network_measures,filename="example.png",label="auto",network_partitioning=None):
p.clf()
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degree
else:
print("not known metric to make layout")
ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
measures=list(ordered_measures.values())
authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
k1=k1=round(total*.80)
k2=k2=round(total*.95)
periphery=authors[:k1]
intermediary=authors[k1:k2]
hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
k1=k1=len(sectors[0])
k2=k2=k1+len(sectors[1])
periphery,intermediary,hubs=(set(iii) for iii in sectors)
in_measures=network_measures.in_strengths
min_in=max(in_measures.values())/3+0.1
out_measures=network_measures.out_strengths
min_out=max(out_measures.values())/3+.1
self.clustering=clustering=network_measures.weighted_clusterings
A=x.drawing.nx_agraph.to_agraph(network.g)
A.node_attr['style']='filled'
A.graph_attr["bgcolor"]="black"
A.graph_attr["pad"]=.1
#A.graph_attr["size"]="9.5,12"
A.graph_attr["fontsize"]="25"
if label=="auto":
label=self.makeLabel()
A.graph_attr["label"]=label
A.graph_attr["fontcolor"]="white"
cm=p.cm.Reds(range(2**10)) # color table
self.cm=cm
nodes=A.nodes()
self.colors=colors=[]
self.inds=inds=[]
self.poss=poss=[]
for node in nodes:
n_=A.get_node(node)
ind_author=self.authors.index(n_)
inds.append(inds)
colors.append( '#%02x%02x%02x' % tuple([int(255*i) for i in cm[int(clustering[n_]*255)][:-1]]))
#n_.attr['fillcolor']= '#%02x%02x%02x' % tuple([255*i for i in cm[int(clustering[n_]*255)][:-1]])
n_.attr['fillcolor']= colors[-1]
n_.attr['fixedsize']=True
n_.attr['width']= abs(.6*(in_measures[n_]/min_in+ .05))
n_.attr['height']= abs(.6*(out_measures[n_]/min_out+.05))
if n_ in hubs:
n_.attr["shape"] = "hexagon"
elif n_ in intermediary:
pass
else:
n_.attr["shape"] = "diamond"
pos="%f,%f"%tuple(self.posXY[ind_author])
poss.append(pos)
n_.attr["pos"]=pos
n_.attr["pin"]=True
n_.attr["fontsize"]=25
n_.attr["fontcolor"]="white"
n_.attr["label"]=""
weights=[s[2]["weight"] for s in network_measures.edges]
self.weights=weights
max_weight=max(weights)
self.max_weight=max_weight
self.weights_=[]
edges=A.edges()
for e in edges:
factor=float(e.attr['weight'])
self.weights_.append(factor)
e.attr['penwidth']=.34*factor
e.attr["arrowsize"]=1.5
e.attr["arrowhead"]="lteeoldiamond"
w=factor/max_weight # factor em [0-1]
cor=p.cm.Spectral(int(w*255))
self.cor=cor
cor256=255*n.array(cor[:-1])
r0=int(cor256[0]/16)
r1=int(cor256[0]-r0*16)
r=hex(r0)[-1]+hex(r1)[-1]
g0=int(cor256[1]/16)
g1=int(cor256[1]-g0*16)
g=hex(g0)[-1]+hex(g1)[-1]
b0=int(cor256[2]/16)
b1=int(cor256[2]-b0*16)
b=hex(b0)[-1]+hex(b1)[-1]
#corRGB="#"+r+g+b+":#"+r+g+b
corRGB="#"+r+g+b
e.attr["color"]=corRGB
A.draw(filename, prog="neato") # twopi ou circo
################
self.A=A
self.draw_count+=1
def makeLabel(self):
label=""
if "window_size" in dir(self):
l | if "step_size" in dir(self):
label+="m: {} ,".format(self.draw_count*self.step_size+self.offset)
else:
label+="m: %i, ".format(self.draw_count)
#self.network_measures.N,self.network_measures.E)
label+="N = %i, E = %i"%(self.network_measures.N,self.network_measures.E)
return label
def updateNetwork(self,network,networkMeasures=None):
pass
def makeXY(self):
size_periphery=self.k1
size_intermediary=self.k2-self.k1
size_hubs=self.network_measures.N-self.k2
if size_hubs%2==1:
size_hubs+=1
size_intermediary-=1
xh=n.linspace(0,0.5,size_hubs,endpoint=False)[::-1]
thetah=2*n.pi*xh
yh=n.sin(thetah)
xi=n.linspace(1,0.5, size_intermediary, endpoint=True)
thetai=2*n.pi*xi
yi=n.sin(thetai)
xp=n.linspace(.95,0.4, size_periphery)[::-1]
yp=n.linspace(.1,1.25, size_periphery)[::-1]
self.pos=((xp,yp),(xi,yi),(xh,yh))
XFACT=7
YFACT=3
self.posX=posX=n.hstack((xp,xi,xh))*XFACT
self.posY=posY=n.hstack((yp,yi,yh))*YFACT
self.posXY=n.vstack((posX.T,posY.T)).T
| abel+="w: {}, ".format(self.window_size)
#m: %i, N = %i, E = %i"%(self.draw_count*self.step_size,self.network_measures.N,self.network_measures.E)
| conditional_block |
networkDrawer.py | import sys
import collections as c
from scipy import special, stats
import numpy as n, pylab as p, networkx as x
class NetworkDrawer:
drawer_count=0
def __init__(self,metric="strength"):
self.drawer_count+=1
metric_=self.standardizeName(metric)
self.metric_=metric_
self.draw_count=0
def | (self,name):
if name in (["s","strength","st"]+["f","força","forca","fo"]):
name_="s"
if name in (["d","degree","dg"]+["g","grau","gr"]):
name_="d"
return name_
def makeLayout(self,network_measures,network_partitioning=None):
"""Delivers a sequence of user_ids and (x,y) pos.
"""
self.network_measures=network_measures
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degrees
else:
print("not known metric to make layout")
self.ordered_measures=ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
self.measures=measures=list(ordered_measures.values())
self.authors=authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
self.k1=k1=round(total*.80)
self.k2=k2=round(total*.95)
self.periphery=authors[:k1]
self.intermediary=authors[k1:k2]
self.hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
self.k1=k1=len(sectors[0])
self.k2=k2=k1+len(sectors[1])
self.periphery,self.intermediary,self.hubs=sectors
print("fractions ={:0.4f}, {:0.4f}, {:0.4f}".format(k1/total, (k2-k1)/total, 1-k2/total))
self.makeXY()
def drawNetwork(self, network,network_measures,filename="example.png",label="auto",network_partitioning=None):
p.clf()
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degree
else:
print("not known metric to make layout")
ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
measures=list(ordered_measures.values())
authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
k1=k1=round(total*.80)
k2=k2=round(total*.95)
periphery=authors[:k1]
intermediary=authors[k1:k2]
hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
k1=k1=len(sectors[0])
k2=k2=k1+len(sectors[1])
periphery,intermediary,hubs=(set(iii) for iii in sectors)
in_measures=network_measures.in_strengths
min_in=max(in_measures.values())/3+0.1
out_measures=network_measures.out_strengths
min_out=max(out_measures.values())/3+.1
self.clustering=clustering=network_measures.weighted_clusterings
A=x.drawing.nx_agraph.to_agraph(network.g)
A.node_attr['style']='filled'
A.graph_attr["bgcolor"]="black"
A.graph_attr["pad"]=.1
#A.graph_attr["size"]="9.5,12"
A.graph_attr["fontsize"]="25"
if label=="auto":
label=self.makeLabel()
A.graph_attr["label"]=label
A.graph_attr["fontcolor"]="white"
cm=p.cm.Reds(range(2**10)) # color table
self.cm=cm
nodes=A.nodes()
self.colors=colors=[]
self.inds=inds=[]
self.poss=poss=[]
for node in nodes:
n_=A.get_node(node)
ind_author=self.authors.index(n_)
inds.append(inds)
colors.append( '#%02x%02x%02x' % tuple([int(255*i) for i in cm[int(clustering[n_]*255)][:-1]]))
#n_.attr['fillcolor']= '#%02x%02x%02x' % tuple([255*i for i in cm[int(clustering[n_]*255)][:-1]])
n_.attr['fillcolor']= colors[-1]
n_.attr['fixedsize']=True
n_.attr['width']= abs(.6*(in_measures[n_]/min_in+ .05))
n_.attr['height']= abs(.6*(out_measures[n_]/min_out+.05))
if n_ in hubs:
n_.attr["shape"] = "hexagon"
elif n_ in intermediary:
pass
else:
n_.attr["shape"] = "diamond"
pos="%f,%f"%tuple(self.posXY[ind_author])
poss.append(pos)
n_.attr["pos"]=pos
n_.attr["pin"]=True
n_.attr["fontsize"]=25
n_.attr["fontcolor"]="white"
n_.attr["label"]=""
weights=[s[2]["weight"] for s in network_measures.edges]
self.weights=weights
max_weight=max(weights)
self.max_weight=max_weight
self.weights_=[]
edges=A.edges()
for e in edges:
factor=float(e.attr['weight'])
self.weights_.append(factor)
e.attr['penwidth']=.34*factor
e.attr["arrowsize"]=1.5
e.attr["arrowhead"]="lteeoldiamond"
w=factor/max_weight # factor em [0-1]
cor=p.cm.Spectral(int(w*255))
self.cor=cor
cor256=255*n.array(cor[:-1])
r0=int(cor256[0]/16)
r1=int(cor256[0]-r0*16)
r=hex(r0)[-1]+hex(r1)[-1]
g0=int(cor256[1]/16)
g1=int(cor256[1]-g0*16)
g=hex(g0)[-1]+hex(g1)[-1]
b0=int(cor256[2]/16)
b1=int(cor256[2]-b0*16)
b=hex(b0)[-1]+hex(b1)[-1]
#corRGB="#"+r+g+b+":#"+r+g+b
corRGB="#"+r+g+b
e.attr["color"]=corRGB
A.draw(filename, prog="neato") # twopi ou circo
################
self.A=A
self.draw_count+=1
def makeLabel(self):
label=""
if "window_size" in dir(self):
label+="w: {}, ".format(self.window_size)
#m: %i, N = %i, E = %i"%(self.draw_count*self.step_size,self.network_measures.N,self.network_measures.E)
if "step_size" in dir(self):
label+="m: {} ,".format(self.draw_count*self.step_size+self.offset)
else:
label+="m: %i, ".format(self.draw_count)
#self.network_measures.N,self.network_measures.E)
label+="N = %i, E = %i"%(self.network_measures.N,self.network_measures.E)
return label
def updateNetwork(self,network,networkMeasures=None):
pass
def makeXY(self):
size_periphery=self.k1
size_intermediary=self.k2-self.k1
size_hubs=self.network_measures.N-self.k2
if size_hubs%2==1:
size_hubs+=1
size_intermediary-=1
xh=n.linspace(0,0.5,size_hubs,endpoint=False)[::-1]
thetah=2*n.pi*xh
yh=n.sin(thetah)
xi=n.linspace(1,0.5, size_intermediary, endpoint=True)
thetai=2*n.pi*xi
yi=n.sin(thetai)
xp=n.linspace(.95,0.4, size_periphery)[::-1]
yp=n.linspace(.1,1.25, size_periphery)[::-1]
self.pos=((xp,yp),(xi,yi),(xh,yh))
XFACT=7
YFACT=3
self.posX=posX=n.hstack((xp,xi,xh))*XFACT
self.posY=posY=n.hstack((yp,yi,yh))*YFACT
self.posXY=n.vstack((posX.T,posY.T)).T
| standardizeName | identifier_name |
networkDrawer.py | import sys
import collections as c
from scipy import special, stats
import numpy as n, pylab as p, networkx as x
class NetworkDrawer:
drawer_count=0
def __init__(self,metric="strength"):
self.drawer_count+=1
metric_=self.standardizeName(metric)
self.metric_=metric_
self.draw_count=0
def standardizeName(self,name):
if name in (["s","strength","st"]+["f","força","forca","fo"]):
name_="s"
if name in (["d","degree","dg"]+["g","grau","gr"]):
name_="d"
return name_
def makeLayout(self,network_measures,network_partitioning=None):
"""Delivers a sequence of user_ids and (x,y) pos.
"""
self.network_measures=network_measures
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degrees
else:
print("not known metric to make layout")
self.ordered_measures=ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
self.measures=measures=list(ordered_measures.values())
self.authors=authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
self.k1=k1=round(total*.80)
self.k2=k2=round(total*.95)
self.periphery=authors[:k1]
self.intermediary=authors[k1:k2]
self.hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
self.k1=k1=len(sectors[0])
self.k2=k2=k1+len(sectors[1])
self.periphery,self.intermediary,self.hubs=sectors
print("fractions ={:0.4f}, {:0.4f}, {:0.4f}".format(k1/total, (k2-k1)/total, 1-k2/total))
self.makeXY()
def drawNetwork(self, network,network_measures,filename="example.png",label="auto",network_partitioning=None):
p.clf()
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degree
else:
print("not known metric to make layout")
ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
measures=list(ordered_measures.values())
authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
k1=k1=round(total*.80)
k2=k2=round(total*.95)
periphery=authors[:k1]
intermediary=authors[k1:k2]
hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
k1=k1=len(sectors[0])
k2=k2=k1+len(sectors[1])
periphery,intermediary,hubs=(set(iii) for iii in sectors)
in_measures=network_measures.in_strengths
min_in=max(in_measures.values())/3+0.1
out_measures=network_measures.out_strengths
min_out=max(out_measures.values())/3+.1
self.clustering=clustering=network_measures.weighted_clusterings
A=x.drawing.nx_agraph.to_agraph(network.g)
A.node_attr['style']='filled'
A.graph_attr["bgcolor"]="black"
A.graph_attr["pad"]=.1
#A.graph_attr["size"]="9.5,12"
A.graph_attr["fontsize"]="25"
if label=="auto":
label=self.makeLabel()
A.graph_attr["label"]=label
A.graph_attr["fontcolor"]="white"
cm=p.cm.Reds(range(2**10)) # color table
self.cm=cm
nodes=A.nodes()
self.colors=colors=[]
self.inds=inds=[]
self.poss=poss=[]
for node in nodes:
n_=A.get_node(node)
ind_author=self.authors.index(n_)
inds.append(inds)
colors.append( '#%02x%02x%02x' % tuple([int(255*i) for i in cm[int(clustering[n_]*255)][:-1]]))
#n_.attr['fillcolor']= '#%02x%02x%02x' % tuple([255*i for i in cm[int(clustering[n_]*255)][:-1]])
n_.attr['fillcolor']= colors[-1]
n_.attr['fixedsize']=True
n_.attr['width']= abs(.6*(in_measures[n_]/min_in+ .05))
n_.attr['height']= abs(.6*(out_measures[n_]/min_out+.05))
if n_ in hubs:
n_.attr["shape"] = "hexagon"
elif n_ in intermediary:
pass
else:
n_.attr["shape"] = "diamond"
pos="%f,%f"%tuple(self.posXY[ind_author])
poss.append(pos)
n_.attr["pos"]=pos
n_.attr["pin"]=True
n_.attr["fontsize"]=25
n_.attr["fontcolor"]="white"
n_.attr["label"]=""
weights=[s[2]["weight"] for s in network_measures.edges]
self.weights=weights
max_weight=max(weights)
self.max_weight=max_weight
self.weights_=[]
edges=A.edges()
for e in edges:
factor=float(e.attr['weight'])
self.weights_.append(factor)
e.attr['penwidth']=.34*factor
e.attr["arrowsize"]=1.5
e.attr["arrowhead"]="lteeoldiamond"
w=factor/max_weight # factor em [0-1]
cor=p.cm.Spectral(int(w*255))
self.cor=cor
cor256=255*n.array(cor[:-1])
r0=int(cor256[0]/16)
r1=int(cor256[0]-r0*16)
r=hex(r0)[-1]+hex(r1)[-1]
g0=int(cor256[1]/16)
g1=int(cor256[1]-g0*16)
g=hex(g0)[-1]+hex(g1)[-1]
b0=int(cor256[2]/16)
b1=int(cor256[2]-b0*16)
b=hex(b0)[-1]+hex(b1)[-1]
#corRGB="#"+r+g+b+":#"+r+g+b
corRGB="#"+r+g+b
e.attr["color"]=corRGB
A.draw(filename, prog="neato") # twopi ou circo
################
self.A=A
self.draw_count+=1
def makeLabel(self):
l |
def updateNetwork(self,network,networkMeasures=None):
pass
def makeXY(self):
size_periphery=self.k1
size_intermediary=self.k2-self.k1
size_hubs=self.network_measures.N-self.k2
if size_hubs%2==1:
size_hubs+=1
size_intermediary-=1
xh=n.linspace(0,0.5,size_hubs,endpoint=False)[::-1]
thetah=2*n.pi*xh
yh=n.sin(thetah)
xi=n.linspace(1,0.5, size_intermediary, endpoint=True)
thetai=2*n.pi*xi
yi=n.sin(thetai)
xp=n.linspace(.95,0.4, size_periphery)[::-1]
yp=n.linspace(.1,1.25, size_periphery)[::-1]
self.pos=((xp,yp),(xi,yi),(xh,yh))
XFACT=7
YFACT=3
self.posX=posX=n.hstack((xp,xi,xh))*XFACT
self.posY=posY=n.hstack((yp,yi,yh))*YFACT
self.posXY=n.vstack((posX.T,posY.T)).T
| abel=""
if "window_size" in dir(self):
label+="w: {}, ".format(self.window_size)
#m: %i, N = %i, E = %i"%(self.draw_count*self.step_size,self.network_measures.N,self.network_measures.E)
if "step_size" in dir(self):
label+="m: {} ,".format(self.draw_count*self.step_size+self.offset)
else:
label+="m: %i, ".format(self.draw_count)
#self.network_measures.N,self.network_measures.E)
label+="N = %i, E = %i"%(self.network_measures.N,self.network_measures.E)
return label
| identifier_body |
networkDrawer.py | import sys
import collections as c
from scipy import special, stats
import numpy as n, pylab as p, networkx as x
class NetworkDrawer:
drawer_count=0
def __init__(self,metric="strength"):
self.drawer_count+=1
metric_=self.standardizeName(metric)
self.metric_=metric_
self.draw_count=0
def standardizeName(self,name):
if name in (["s","strength","st"]+["f","força","forca","fo"]):
name_="s"
if name in (["d","degree","dg"]+["g","grau","gr"]):
name_="d"
return name_
def makeLayout(self,network_measures,network_partitioning=None):
"""Delivers a sequence of user_ids and (x,y) pos.
"""
self.network_measures=network_measures
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degrees
else:
print("not known metric to make layout")
self.ordered_measures=ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
self.measures=measures=list(ordered_measures.values())
self.authors=authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
self.k1=k1=round(total*.80)
self.k2=k2=round(total*.95)
self.periphery=authors[:k1]
self.intermediary=authors[k1:k2]
self.hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
self.k1=k1=len(sectors[0])
self.k2=k2=k1+len(sectors[1])
self.periphery,self.intermediary,self.hubs=sectors
print("fractions ={:0.4f}, {:0.4f}, {:0.4f}".format(k1/total, (k2-k1)/total, 1-k2/total))
self.makeXY()
def drawNetwork(self, network,network_measures,filename="example.png",label="auto",network_partitioning=None):
p.clf()
if self.metric_=="s":
measures_=network_measures.strengths
elif self.metric_=="d":
measures_=network_measures.degree
else:
print("not known metric to make layout")
ordered_measures = c.OrderedDict(sorted(measures_.items(), key=lambda x: x[1]))
measures=list(ordered_measures.values())
authors= list(ordered_measures.keys())
total=network_measures.N
if not network_partitioning:
k1=k1=round(total*.80)
k2=k2=round(total*.95)
periphery=authors[:k1]
intermediary=authors[k1:k2]
hubs=authors[k2:]
else:
sectors=network_partitioning.sectorialized_agents__
k1=k1=len(sectors[0])
k2=k2=k1+len(sectors[1])
periphery,intermediary,hubs=(set(iii) for iii in sectors)
in_measures=network_measures.in_strengths
min_in=max(in_measures.values())/3+0.1
out_measures=network_measures.out_strengths
min_out=max(out_measures.values())/3+.1
self.clustering=clustering=network_measures.weighted_clusterings
A=x.drawing.nx_agraph.to_agraph(network.g)
A.node_attr['style']='filled'
A.graph_attr["bgcolor"]="black"
A.graph_attr["pad"]=.1 | A.graph_attr["label"]=label
A.graph_attr["fontcolor"]="white"
cm=p.cm.Reds(range(2**10)) # color table
self.cm=cm
nodes=A.nodes()
self.colors=colors=[]
self.inds=inds=[]
self.poss=poss=[]
for node in nodes:
n_=A.get_node(node)
ind_author=self.authors.index(n_)
inds.append(inds)
colors.append( '#%02x%02x%02x' % tuple([int(255*i) for i in cm[int(clustering[n_]*255)][:-1]]))
#n_.attr['fillcolor']= '#%02x%02x%02x' % tuple([255*i for i in cm[int(clustering[n_]*255)][:-1]])
n_.attr['fillcolor']= colors[-1]
n_.attr['fixedsize']=True
n_.attr['width']= abs(.6*(in_measures[n_]/min_in+ .05))
n_.attr['height']= abs(.6*(out_measures[n_]/min_out+.05))
if n_ in hubs:
n_.attr["shape"] = "hexagon"
elif n_ in intermediary:
pass
else:
n_.attr["shape"] = "diamond"
pos="%f,%f"%tuple(self.posXY[ind_author])
poss.append(pos)
n_.attr["pos"]=pos
n_.attr["pin"]=True
n_.attr["fontsize"]=25
n_.attr["fontcolor"]="white"
n_.attr["label"]=""
weights=[s[2]["weight"] for s in network_measures.edges]
self.weights=weights
max_weight=max(weights)
self.max_weight=max_weight
self.weights_=[]
edges=A.edges()
for e in edges:
factor=float(e.attr['weight'])
self.weights_.append(factor)
e.attr['penwidth']=.34*factor
e.attr["arrowsize"]=1.5
e.attr["arrowhead"]="lteeoldiamond"
w=factor/max_weight # factor em [0-1]
cor=p.cm.Spectral(int(w*255))
self.cor=cor
cor256=255*n.array(cor[:-1])
r0=int(cor256[0]/16)
r1=int(cor256[0]-r0*16)
r=hex(r0)[-1]+hex(r1)[-1]
g0=int(cor256[1]/16)
g1=int(cor256[1]-g0*16)
g=hex(g0)[-1]+hex(g1)[-1]
b0=int(cor256[2]/16)
b1=int(cor256[2]-b0*16)
b=hex(b0)[-1]+hex(b1)[-1]
#corRGB="#"+r+g+b+":#"+r+g+b
corRGB="#"+r+g+b
e.attr["color"]=corRGB
A.draw(filename, prog="neato") # twopi ou circo
################
self.A=A
self.draw_count+=1
def makeLabel(self):
label=""
if "window_size" in dir(self):
label+="w: {}, ".format(self.window_size)
#m: %i, N = %i, E = %i"%(self.draw_count*self.step_size,self.network_measures.N,self.network_measures.E)
if "step_size" in dir(self):
label+="m: {} ,".format(self.draw_count*self.step_size+self.offset)
else:
label+="m: %i, ".format(self.draw_count)
#self.network_measures.N,self.network_measures.E)
label+="N = %i, E = %i"%(self.network_measures.N,self.network_measures.E)
return label
def updateNetwork(self,network,networkMeasures=None):
pass
def makeXY(self):
size_periphery=self.k1
size_intermediary=self.k2-self.k1
size_hubs=self.network_measures.N-self.k2
if size_hubs%2==1:
size_hubs+=1
size_intermediary-=1
xh=n.linspace(0,0.5,size_hubs,endpoint=False)[::-1]
thetah=2*n.pi*xh
yh=n.sin(thetah)
xi=n.linspace(1,0.5, size_intermediary, endpoint=True)
thetai=2*n.pi*xi
yi=n.sin(thetai)
xp=n.linspace(.95,0.4, size_periphery)[::-1]
yp=n.linspace(.1,1.25, size_periphery)[::-1]
self.pos=((xp,yp),(xi,yi),(xh,yh))
XFACT=7
YFACT=3
self.posX=posX=n.hstack((xp,xi,xh))*XFACT
self.posY=posY=n.hstack((yp,yi,yh))*YFACT
self.posXY=n.vstack((posX.T,posY.T)).T | #A.graph_attr["size"]="9.5,12"
A.graph_attr["fontsize"]="25"
if label=="auto":
label=self.makeLabel() | random_line_split |
index.js | var on = require('emmy/on');
var off = require('emmy/off');
module.exports = Sticky;
/**
* @constructor
*/
function Sticky(el, options){
if (el.getAttribute('data-sticky-id') === undefined) {
return console.log('Sticky already exist');
}
this.el = el;
this.parent = this.el.parentNode;
//recognize attributes
var dataset = el.dataset;
if (!dataset){
dataset = {};
if (el.getAttribute('data-within')) dataset['within'] = el.getAttribute('data-within');
if (el.getAttribute('data-offset')) dataset['offset'] = el.getAttribute('data-offset');
if (el.getAttribute('data-stack')) dataset['stack'] = el.getAttribute('data-stack');
if (el.getAttribute('data-sticky-class')) dataset['stickyClass'] = el.getAttribute('data-sticky-class');
}
this.options = Object.assign({}, this.options, dataset, options);
//query selector, if passed one
if ( typeof this.options['within'] === 'string' && this.options['within'].trim() ){
this.within = document.body.querySelector(this.options['within']);
} else {
this.within = this.options['within'];
}
//keep list
this.el.setAttribute('data-sticky-id', Sticky.list.length);
this.id = Sticky.list.length;
Sticky.list.push(this);
//state
this.isFixed = false;
this.isBottom = false;
this.isTop = true;
this.updateClasses();
//boundaries to strict within
this.restrictBox = {
top: 0,
bottom: 9999
};
//self position & size
this.height = 0;
this.isDisabled = false;
//parent position & size
this.parentBox = {
top: 0,
height: 0
}
//mind gap from bottom & top in addition to restrictBox (for stacks)
this.options.offset = parseFloat(this.options['offset']) || 0;
this.offset = {
top: 0,
bottom: 0
};
//additional gap if item being scrolled
this.scrollOffset = 0;
//Detect whether stacking is needed
var prevEl = this.el;
this.stackId = [];
this.stack = [];
if (this.options['stack']) {
var stack = this.options['stack'].split(',');
for (var i = stack.length; i--;){
stack[i] = stack[i].trim();
if (!Sticky.stack[stack[i]]) Sticky.stack[stack[i]] = [];
this.stackId[i] = Sticky.stack[stack[i]].length;
this.stack.push(stack[i]);
Sticky.stack[stack[i]].push(this)
}
} else {
this.stackId[0] = Sticky.noStack.length;
Sticky.noStack.push(this);
}
//stub is a spacer filling space when element is stuck
this.stub = this.el.cloneNode();
this.stub.classList.add(this.options['stubClass']);
this.stub.style.visibility = 'hidden';
this.stub.style.display = 'none';
this.stub.removeAttribute('hidden');
//save initial inline style
this.initialStyle = this.el.style.cssText;
this.initialDisplay = getComputedStyle(this.el)['display'];
//ensure parent's container relative coordinates
var pStyle = getComputedStyle(this.parent);
if (pStyle.position == 'static') this.parent.style.position = 'relative';
//bind methods
this.check = this.check.bind(this);
this.recalc = this.recalc.bind(this);
this.disable = this.disable.bind(this);
this.enable = this.enable.bind(this);
this.bindEvents = this.bindEvents.bind(this);
this.adjustSizeAndPosition = this.adjustSizeAndPosition.bind(this);
this.park = this.park.bind(this);
this.stick = this.stick.bind(this);
this.parkStack = this.parkStack.bind(this);
this.stickStack = this.stickStack.bind(this);
this.captureScrollOffset = this.captureScrollOffset.bind(this);
this.observeStackScroll = this.observeStackScroll.bind(this);
this.stopObservingStackScroll = this.stopObservingStackScroll.bind(this);
if (this.initialDisplay === 'none') {
this.initialDisplay = 'block';
this.disable();
}
else this.enable();
}
//list of instances
Sticky.list = [];
//mutually exclusive items
Sticky.noStack = [];
//stacks of items
Sticky.stack = {};
//heights of stacks
Sticky.stackHeights = {};
/** Update all sticky instances */
Sticky.recalc = function () {
Sticky.list.forEach(function (instance) {
instance.recalc();
});
};
/** API events */
on(document, 'sticky:recalc', Sticky.recalc);
var proto = Sticky.prototype;
proto.options = {
'offset': 0,
'within': null, //element or bounding box
'stubClass': 'sticky-stub',
'stickyClass': 'is-stuck',
'bottomClass': 'is-bottom',
'topClass': 'is-top',
'stack': null,
'collapse': true,
'recalcInterval': 20
};
/** when element removed or made hidden. */ | proto.disable = function(){
if (this.stub.parentNode) this.parent.removeChild(this.stub);
this.unbindEvents();
this.isDisabled = true;
Sticky.recalc();
};
/** enables previously disabled element */
proto.enable = function(){
if (!this.stub.parentNode) this.parent.insertBefore(this.stub, this.el);
this.isDisabled = false;
this.bindEvents();
Sticky.recalc();
};
proto.bindEvents = function(){
on(document, 'scroll', this.check);
on(window, 'resize', this.recalc);
on(this.el, 'mouseover', this.observeStackScroll);
on(this.el, 'mouseout', this.stopObservingStackScroll);
};
proto.unbindEvents = function(){
off(document, 'scroll', this.check);
off(window, 'resize', this.recalc);
off(this.el, 'mouseover', this.observeStackScroll);
off(this.el, 'mouseout', this.stopObservingStackScroll);
};
/** changing state necessity checker */
proto.check = function(){
var vpTop = window.pageYOffset || document.documentElement.scrollTop;
//console.log('check:' + this.el.dataset['stickyId'], 'isFixed:' + this.isFixed, this.restrictBox)
if (this.isFixed){
if (!this.isTop && vpTop + this.offset.top + this.options.offset + this.height + this.mt + this.mb + this.scrollOffset >= this.restrictBox.bottom - this.offset.bottom){
//check bottom parking needed
this.parkBottom();
}
if (!this.isBottom && vpTop + this.offset.top + this.options.offset + this.mt + this.scrollOffset <= this.restrictBox.top){
//check top parking needed
this.parkTop();
}
} else {
if (this.isTop || this.isBottom){
if (vpTop + this.offset.top + this.options.offset + this.mt > this.restrictBox.top){
//fringe violation from top
if (vpTop + this.offset.top + this.options.offset + this.height + this.mt + this.mb < this.restrictBox.bottom - this.offset.bottom){
//fringe violation from top or bottom to the sticking zone
this.stick();
} else if (!this.isBottom) {
//fringe violation from top lower than bottom
this.stick();
this.parkBottom();
}
} else if(this.isBottom){
//fringe violation from bottom to higher than top
this.stick();
this.parkTop();
}
}
}
};
/**
* sticking inner routines
* when park top needed
*/
proto.parkTop = function(){
//this.el = this.parent.removeChild(this.el);
this.el.style.cssText = this.initialStyle;
//this.stub = this.parent.replaceChild(this.el, this.stub);
this.stub.style.display = 'none';
this.scrollOffset = 0;
this.isFixed = false;
this.isTop = true;
this.isBottom = false;
this.updateClasses();
this.isStackParked = true;
// console.log('parkTop', this.id)
};
/** when stop needed somewhere in between top and bottom */
proto.park = function(){
// console.log('parkMiddle', this.id)
this.isFixed = false;
this.isTop = false;
this.isBottom = false;
this.updateClasses();
this.isStackParked = true;
var offset = (window.pageYOffset || document.documentElement.scrollTop) + this.offset.top - this.parentBox.top + this.scrollOffset;
this.makeParkedStyle(offset);
};
/**
* to make fixed
* enhanced replace: faked visual stub is fastly replaced with natural one
*/
proto.stick = function(){
//this.el = this.parent.replaceChild(this.stub, this.el);
this.stub.style.display = this.initialDisplay;
this.makeStickedStyle();
//this.parent.insertBefore(this.el, this.stub);
this.isFixed = true;
this.isTop = false;
this.isBottom = false;
this.updateClasses();
this.isStackParked = false;
// console.log('stick', this.id)
};
/** when bottom land needed */
proto.parkBottom = function(){
this.makeParkedBottomStyle();
this.scrollOffset = 0;
this.isFixed = false;
this.isBottom = true;
this.isTop = false;
this.updateClasses();
this.isStackParked = true;
// console.log('parkBottom', this.id)
};
/**
* park all items within stack passed/all stacks of this
* used when item was scrolled on
*/
proto.parkStack = function(){
var stack = Sticky.stack[this.stack[0]];
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.park();
}
};
/** unpark all items of stack passed */
proto.stickStack = function(){
var stack = Sticky.stack[this.stack[0]]
var first = stack[0], last = stack[stack.length - 1];
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.stick();
}
};
/**
* begin observing scroll to park stack
*/
proto.observeStackScroll = function(){
var stack = Sticky.stack[this.stack[0]]
if (!stack) return;
var first = stack[0], last = stack[stack.length - 1];
//if stack is parked top or parked bottom - ignore
if (first.isTop || last.isTop) return;
//if stack isn’t higher than window height - ignore
if (Sticky.stackHeights[this.stack[0]] <= window.innerHeight && this.scrollOffset >= 0) return;
//capture stack’s scroll
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop) + this.scrollOffset;
on(document, 'scroll', this.captureScrollOffset);
return this;
};
/** stop observing scroll */
proto.stopObservingStackScroll = function(){
var stack = Sticky.stack[this.stack[0]];
if (!stack) return;
var last = stack[stack.length-1], first = stack[0];
off(document, 'scroll', this.captureScrollOffset);
if (first.isTop || first.isBottom || last.isTop || last.isBottom) {
return;
}
if (this.isStackParked) this.stickStack();
};
/** when item was scrolled on - capture how much it is scrolled */
proto.captureScrollOffset = function(e){
var scrollOffset = this.scrollStartOffset - (window.pageYOffset || document.documentElement.scrollTop);
var stack = Sticky.stack[this.stack[0]];
var last = stack[stack.length-1], first = stack[0];
//ignore outside sticking
if (first.isTop || first.isBottom || last.isTop || last.isBottom) {
return;
}
var stickNeeded = false, parkNeeded = false;
//if bottom is higher or equal than viewport’s bottom - stick within viewport
if ( scrollOffset < window.innerHeight - (Sticky.stackHeights[this.stack[0]]) ){
scrollOffset = window.innerHeight - (Sticky.stackHeights[this.stack[0]]);
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop) + scrollOffset;
stickNeeded = true;
}
//if top is lower or equal to the viewport’s top - stick within viewport
else if ( scrollOffset > 0){
scrollOffset = 0;
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop);
stickNeeded = true;
}
//if stack items is somewhere in between
else if (!this.isStackParked ){
parkNeeded = true;
}
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.scrollOffset = scrollOffset
}
if (stickNeeded && this.isStackParked) return this.stickStack();
else if (parkNeeded && !this.isStackParked) return this.parkStack();
};
/** set up style of element as if it is parked somewhere / at the bottom */
proto.makeParkedStyle = function(top){
this.el.style.cssText = this.initialStyle;
this.el.style.position = 'absolute';
this.el.style.top = top + 'px';
mimicStyle(this.el, this.stub);
this.el.style.left = this.stub.offsetLeft + 'px';
};
proto.makeParkedBottomStyle = function(){
this.makeParkedStyle(this.restrictBox.bottom - this.offset.bottom - this.parentBox.top - this.height - this.mt - this.mb);
};
proto.makeStickedStyle = function(){
this.el.style.cssText = this.initialStyle;
this.el.style.position = 'fixed';
this.el.style.top = this.offset.top + this.options.offset + this.scrollOffset + 'px';
mimicStyle(this.el, this.stub);
};
//makes element classes reflecting it's state (this.isTop, this.isBottom, this.isFixed)
proto.updateClasses = function(){
if (this.isTop){
this.el.classList.add(this.options['topClass']);
} else {
this.el.classList.remove(this.options['topClass']);
}
if (this.isFixed){
this.el.classList.add(this.options['stickyClass']);
} else {
this.el.classList.remove(this.options['stickyClass']);
}
if (this.isBottom){
this.el.classList.add(this.options['bottomClass']);
} else {
this.el.classList.remove(this.options['bottomClass']);
}
};
proto.recalc = function(){
//console.group('recalc:' + this.el.dataset['stickyId'])
//element to mimic visual properties from
var measureEl = (this.isTop ? this.el : this.stub);
//update stub content
this.stub.innerHTML = this.el.innerHTML;
cleanNode(this.stub);
//update parent container size & offsets
this.parentBox = getOffset(this.parent);
//update self size & position
this.height = this.el.offsetHeight;
var mStyle = getComputedStyle(measureEl);
this.ml = ~~mStyle.marginLeft.slice(0,-2);
this.mr = ~~mStyle.marginRight.slice(0,-2);
this.mt = ~~mStyle.marginTop.slice(0,-2);
this.mb = ~~mStyle.marginBottom.slice(0,-2);
this.scrollOffset = 0;
//update restrictions
this.restrictBox = this.getRestrictBox(this.within, measureEl);
//make restriction up to next sibling within one container
var prevSticky;
this.offset.bottom = 0;
this.offset.top = 0;
if (this.stack.length){
for (var i = this.stack.length; i--;){
if (prevSticky = Sticky.stack[this.stack[i]][this.stackId[i] - 1]){
//make offsets for stacked mode
var prevMeasurer = (prevSticky.isTop ? prevSticky.el : prevSticky.stub);
this.offset.top = prevSticky.offset.top + prevSticky.options.offset;
if (!(this.options['collapse'] && !isOverlap(measureEl, prevMeasurer))) {
this.offset.top += prevSticky.height + Math.max(prevSticky.mt, prevSticky.mb)//collapsed margin
var nextSticky = Sticky.stack[this.stack[i]][this.stackId[i]];
//multistacking-way of correcting bottom offsets
for( var j = this.stackId[i] - 1; (prevSticky = Sticky.stack[this.stack[i]][j]); j--){
prevSticky.offset.bottom = Math.max(prevSticky.offset.bottom, nextSticky.offset.bottom + nextSticky.height + nextSticky.mt + nextSticky.mb);
nextSticky = prevSticky;
}
}
}
//track stack heights;
Sticky.stackHeights[this.stack[i]] = this.offset.top + this.height + this.mt + this.mb;
}
} else if (prevSticky = Sticky.noStack[this.stackId[0] - 1]){
prevSticky.restrictBox.bottom = this.restrictBox.top - this.mt;
}
clearTimeout(this._updTimeout);
this._updTimeout = setTimeout(this.adjustSizeAndPosition, 0);
};
/**
* return box with sizes based on any restrictwithin object passed
*/
proto.getRestrictBox = function(within, measureEl){
var restrictBox = {
top: 0,
bottom: 0
};
if (within instanceof Element){
var offsetRect = getOffset(within)
restrictBox.top = Math.max(offsetRect.top, getOffset(measureEl).top);
//console.log(getOffset(this.stub))
restrictBox.bottom = within.offsetHeight + offsetRect.top;
} else if (within instanceof Object) {
if (within.top instanceof Element) {
var offsetRect = getOffset(within.top)
restrictBox.top = Math.max(offsetRect.top, getOffset(measureEl).top);
} else {
restrictBox.top = within.top;
}
if (within.bottom instanceof Element) {
var offsetRect = getOffset(within.bottom)
restrictBox.bottom = within.bottom.offsetHeight + offsetRect.top;
//console.log(offsetRect)
} else {
restrictBox.bottom = within.bottom;
}
} else {
//case of parent container
restrictBox.top = getOffset(measureEl).top;
restrictBox.bottom = this.parentBox.height + this.parentBox.top;
}
//console.log('Restrictbox', restrictBox)
return restrictBox;
};
proto.adjustSizeAndPosition = function(){
if (this.isTop){
this.el.style.cssText = this.initialStyle;
} else if (this.isBottom){
this.makeParkedBottomStyle();
} else {
this.makeStickedStyle();
}
this.check();
};
/** removes iframe, objects etc shit */
var badTags = ['object', 'iframe', 'embed', 'img'];
function cleanNode(node){
node.removeAttribute('id');
var idTags = node.querySelectorAll('[id]');
for (var k = 0; k < idTags.length; k++){
idTags[k].removeAttribute('id'); //avoid any uniqueness
idTags[k].removeAttribute('name'); //avoid any uniqueness
}
for (var i = 0; i < badTags.length; i++){
var tags = node.querySelectorAll(badTags[i]);
for (var j = tags.length; j--; ){
if (tags[j].tagName === 'SCRIPT') tags[j].parentNode.replaceChild(tags[j])
tags[j].removeAttribute('src');
tags[j].removeAttribute('href');
tags[j].removeAttribute('rel');
tags[j].removeAttribute('srcdoc');
}
}
}
var directions = ['left', 'top', 'right', 'bottom'],
mimicProperties = ['padding-', 'border-'];
/** copies size-related style of stub */
function mimicStyle(to, from){
var stubStyle = getComputedStyle(from),
stubOffset = getOffset(from),
pl = 0, pr = 0, ml = 0;
if (stubStyle['box-sizing'] !== 'border-box'){
pl = ~~stubStyle.paddingLeft.slice(0,-2)
pr = ~~stubStyle.paddingRight.slice(0,-2)
}
to.style.width = (stubOffset.width - pl - pr) + 'px';
to.style.left = stubOffset.left + 'px';
to.style.marginLeft = 0;
for (var i = 0; i < mimicProperties.length; i++){
for (var j = 0; j < directions.length; j++){
var prop = mimicProperties[i] + directions[j];
to.style[prop] = stubStyle[prop];
}
}
}
/** checks overlapping widths */
function isOverlap(left, right){
var lLeft = left.offsetLeft,
lRight = left.offsetLeft + left.offsetWidth,
rLeft = right.offsetLeft,
rRight = right.offsetWidth + right.offsetLeft;
if (lRight < rLeft && lLeft < rLeft
|| lRight > rRight && lLeft > rRight){
return false;
}
return true;
}
function getOffset(el) {
let rect = el.getBoundingClientRect()
//whether element is or is in fixed
var fixed = isFixed(el);
var xOffset = fixed ? 0 : window.pageXOffset;
var yOffset = fixed ? 0 : window.pageYOffset;
return {
left: rect.left + xOffset,
top: rect.top + yOffset,
width: rect.width,
height: rect.height
};
}
function isFixed (el) {
var parentEl = el;
//window is fixed, btw
if (el === window) return true;
//unlike the doc
if (el === document) return false;
while (parentEl) {
if (getComputedStyle(parentEl).position === 'fixed') return true;
parentEl = parentEl.offsetParent;
}
return false;
} | random_line_split | |
index.js | var on = require('emmy/on');
var off = require('emmy/off');
module.exports = Sticky;
/**
* @constructor
*/
function Sticky(el, options){
if (el.getAttribute('data-sticky-id') === undefined) {
return console.log('Sticky already exist');
}
this.el = el;
this.parent = this.el.parentNode;
//recognize attributes
var dataset = el.dataset;
if (!dataset){
dataset = {};
if (el.getAttribute('data-within')) dataset['within'] = el.getAttribute('data-within');
if (el.getAttribute('data-offset')) dataset['offset'] = el.getAttribute('data-offset');
if (el.getAttribute('data-stack')) dataset['stack'] = el.getAttribute('data-stack');
if (el.getAttribute('data-sticky-class')) dataset['stickyClass'] = el.getAttribute('data-sticky-class');
}
this.options = Object.assign({}, this.options, dataset, options);
//query selector, if passed one
if ( typeof this.options['within'] === 'string' && this.options['within'].trim() ){
this.within = document.body.querySelector(this.options['within']);
} else {
this.within = this.options['within'];
}
//keep list
this.el.setAttribute('data-sticky-id', Sticky.list.length);
this.id = Sticky.list.length;
Sticky.list.push(this);
//state
this.isFixed = false;
this.isBottom = false;
this.isTop = true;
this.updateClasses();
//boundaries to strict within
this.restrictBox = {
top: 0,
bottom: 9999
};
//self position & size
this.height = 0;
this.isDisabled = false;
//parent position & size
this.parentBox = {
top: 0,
height: 0
}
//mind gap from bottom & top in addition to restrictBox (for stacks)
this.options.offset = parseFloat(this.options['offset']) || 0;
this.offset = {
top: 0,
bottom: 0
};
//additional gap if item being scrolled
this.scrollOffset = 0;
//Detect whether stacking is needed
var prevEl = this.el;
this.stackId = [];
this.stack = [];
if (this.options['stack']) {
var stack = this.options['stack'].split(',');
for (var i = stack.length; i--;){
stack[i] = stack[i].trim();
if (!Sticky.stack[stack[i]]) Sticky.stack[stack[i]] = [];
this.stackId[i] = Sticky.stack[stack[i]].length;
this.stack.push(stack[i]);
Sticky.stack[stack[i]].push(this)
}
} else {
this.stackId[0] = Sticky.noStack.length;
Sticky.noStack.push(this);
}
//stub is a spacer filling space when element is stuck
this.stub = this.el.cloneNode();
this.stub.classList.add(this.options['stubClass']);
this.stub.style.visibility = 'hidden';
this.stub.style.display = 'none';
this.stub.removeAttribute('hidden');
//save initial inline style
this.initialStyle = this.el.style.cssText;
this.initialDisplay = getComputedStyle(this.el)['display'];
//ensure parent's container relative coordinates
var pStyle = getComputedStyle(this.parent);
if (pStyle.position == 'static') this.parent.style.position = 'relative';
//bind methods
this.check = this.check.bind(this);
this.recalc = this.recalc.bind(this);
this.disable = this.disable.bind(this);
this.enable = this.enable.bind(this);
this.bindEvents = this.bindEvents.bind(this);
this.adjustSizeAndPosition = this.adjustSizeAndPosition.bind(this);
this.park = this.park.bind(this);
this.stick = this.stick.bind(this);
this.parkStack = this.parkStack.bind(this);
this.stickStack = this.stickStack.bind(this);
this.captureScrollOffset = this.captureScrollOffset.bind(this);
this.observeStackScroll = this.observeStackScroll.bind(this);
this.stopObservingStackScroll = this.stopObservingStackScroll.bind(this);
if (this.initialDisplay === 'none') {
this.initialDisplay = 'block';
this.disable();
}
else this.enable();
}
//list of instances
Sticky.list = [];
//mutually exclusive items
Sticky.noStack = [];
//stacks of items
Sticky.stack = {};
//heights of stacks
Sticky.stackHeights = {};
/** Update all sticky instances */
Sticky.recalc = function () {
Sticky.list.forEach(function (instance) {
instance.recalc();
});
};
/** API events */
on(document, 'sticky:recalc', Sticky.recalc);
var proto = Sticky.prototype;
proto.options = {
'offset': 0,
'within': null, //element or bounding box
'stubClass': 'sticky-stub',
'stickyClass': 'is-stuck',
'bottomClass': 'is-bottom',
'topClass': 'is-top',
'stack': null,
'collapse': true,
'recalcInterval': 20
};
/** when element removed or made hidden. */
proto.disable = function(){
if (this.stub.parentNode) this.parent.removeChild(this.stub);
this.unbindEvents();
this.isDisabled = true;
Sticky.recalc();
};
/** enables previously disabled element */
proto.enable = function(){
if (!this.stub.parentNode) this.parent.insertBefore(this.stub, this.el);
this.isDisabled = false;
this.bindEvents();
Sticky.recalc();
};
proto.bindEvents = function(){
on(document, 'scroll', this.check);
on(window, 'resize', this.recalc);
on(this.el, 'mouseover', this.observeStackScroll);
on(this.el, 'mouseout', this.stopObservingStackScroll);
};
proto.unbindEvents = function(){
off(document, 'scroll', this.check);
off(window, 'resize', this.recalc);
off(this.el, 'mouseover', this.observeStackScroll);
off(this.el, 'mouseout', this.stopObservingStackScroll);
};
/** changing state necessity checker */
proto.check = function(){
var vpTop = window.pageYOffset || document.documentElement.scrollTop;
//console.log('check:' + this.el.dataset['stickyId'], 'isFixed:' + this.isFixed, this.restrictBox)
if (this.isFixed){
if (!this.isTop && vpTop + this.offset.top + this.options.offset + this.height + this.mt + this.mb + this.scrollOffset >= this.restrictBox.bottom - this.offset.bottom){
//check bottom parking needed
this.parkBottom();
}
if (!this.isBottom && vpTop + this.offset.top + this.options.offset + this.mt + this.scrollOffset <= this.restrictBox.top){
//check top parking needed
this.parkTop();
}
} else {
if (this.isTop || this.isBottom){
if (vpTop + this.offset.top + this.options.offset + this.mt > this.restrictBox.top){
//fringe violation from top
if (vpTop + this.offset.top + this.options.offset + this.height + this.mt + this.mb < this.restrictBox.bottom - this.offset.bottom){
//fringe violation from top or bottom to the sticking zone
this.stick();
} else if (!this.isBottom) {
//fringe violation from top lower than bottom
this.stick();
this.parkBottom();
}
} else if(this.isBottom){
//fringe violation from bottom to higher than top
this.stick();
this.parkTop();
}
}
}
};
/**
* sticking inner routines
* when park top needed
*/
proto.parkTop = function(){
//this.el = this.parent.removeChild(this.el);
this.el.style.cssText = this.initialStyle;
//this.stub = this.parent.replaceChild(this.el, this.stub);
this.stub.style.display = 'none';
this.scrollOffset = 0;
this.isFixed = false;
this.isTop = true;
this.isBottom = false;
this.updateClasses();
this.isStackParked = true;
// console.log('parkTop', this.id)
};
/** when stop needed somewhere in between top and bottom */
proto.park = function(){
// console.log('parkMiddle', this.id)
this.isFixed = false;
this.isTop = false;
this.isBottom = false;
this.updateClasses();
this.isStackParked = true;
var offset = (window.pageYOffset || document.documentElement.scrollTop) + this.offset.top - this.parentBox.top + this.scrollOffset;
this.makeParkedStyle(offset);
};
/**
* to make fixed
* enhanced replace: faked visual stub is fastly replaced with natural one
*/
proto.stick = function(){
//this.el = this.parent.replaceChild(this.stub, this.el);
this.stub.style.display = this.initialDisplay;
this.makeStickedStyle();
//this.parent.insertBefore(this.el, this.stub);
this.isFixed = true;
this.isTop = false;
this.isBottom = false;
this.updateClasses();
this.isStackParked = false;
// console.log('stick', this.id)
};
/** when bottom land needed */
proto.parkBottom = function(){
this.makeParkedBottomStyle();
this.scrollOffset = 0;
this.isFixed = false;
this.isBottom = true;
this.isTop = false;
this.updateClasses();
this.isStackParked = true;
// console.log('parkBottom', this.id)
};
/**
* park all items within stack passed/all stacks of this
* used when item was scrolled on
*/
proto.parkStack = function(){
var stack = Sticky.stack[this.stack[0]];
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.park();
}
};
/** unpark all items of stack passed */
proto.stickStack = function(){
var stack = Sticky.stack[this.stack[0]]
var first = stack[0], last = stack[stack.length - 1];
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.stick();
}
};
/**
* begin observing scroll to park stack
*/
proto.observeStackScroll = function(){
var stack = Sticky.stack[this.stack[0]]
if (!stack) return;
var first = stack[0], last = stack[stack.length - 1];
//if stack is parked top or parked bottom - ignore
if (first.isTop || last.isTop) return;
//if stack isn’t higher than window height - ignore
if (Sticky.stackHeights[this.stack[0]] <= window.innerHeight && this.scrollOffset >= 0) return;
//capture stack’s scroll
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop) + this.scrollOffset;
on(document, 'scroll', this.captureScrollOffset);
return this;
};
/** stop observing scroll */
proto.stopObservingStackScroll = function(){
var stack = Sticky.stack[this.stack[0]];
if (!stack) return;
var last = stack[stack.length-1], first = stack[0];
off(document, 'scroll', this.captureScrollOffset);
if (first.isTop || first.isBottom || last.isTop || last.isBottom) {
return;
}
if (this.isStackParked) this.stickStack();
};
/** when item was scrolled on - capture how much it is scrolled */
proto.captureScrollOffset = function(e){
var scrollOffset = this.scrollStartOffset - (window.pageYOffset || document.documentElement.scrollTop);
var stack = Sticky.stack[this.stack[0]];
var last = stack[stack.length-1], first = stack[0];
//ignore outside sticking
if (first.isTop || first.isBottom || last.isTop || last.isBottom) {
return;
}
var stickNeeded = false, parkNeeded = false;
//if bottom is higher or equal than viewport’s bottom - stick within viewport
if ( scrollOffset < window.innerHeight - (Sticky.stackHeights[this.stack[0]]) ){
scrollOffset = window.innerHeight - (Sticky.stackHeights[this.stack[0]]);
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop) + scrollOffset;
stickNeeded = true;
}
//if top is lower or equal to the viewport’s top - stick within viewport
else if ( scrollOffset > 0){
scrollOffset = 0;
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop);
stickNeeded = true;
}
//if stack items is somewhere in between
else if (!this.isStackParked ){
parkNeeded = true;
}
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.scrollOffset = scrollOffset
}
if (stickNeeded && this.isStackParked) return this.stickStack();
else if (parkNeeded && !this.isStackParked) return this.parkStack();
};
/** set up style of element as if it is parked somewhere / at the bottom */
proto.makeParkedStyle = function(top){
this.el.style.cssText = this.initialStyle;
this.el.style.position = 'absolute';
this.el.style.top = top + 'px';
mimicStyle(this.el, this.stub);
this.el.style.left = this.stub.offsetLeft + 'px';
};
proto.makeParkedBottomStyle = function(){
this.makeParkedStyle(this.restrictBox.bottom - this.offset.bottom - this.parentBox.top - this.height - this.mt - this.mb);
};
proto.makeStickedStyle = function(){
this.el.style.cssText = this.initialStyle;
this.el.style.position = 'fixed';
this.el.style.top = this.offset.top + this.options.offset + this.scrollOffset + 'px';
mimicStyle(this.el, this.stub);
};
//makes element classes reflecting it's state (this.isTop, this.isBottom, this.isFixed)
proto.updateClasses = function(){
if (this.isTop){
this.el.classList.add(this.options['topClass']);
} else {
this.el.classList.remove(this.options['topClass']);
}
if (this.isFixed){
this.el.classList.add(this.options['stickyClass']);
} else {
this.el.classList.remove(this.options['stickyClass']);
}
if (this.isBottom){
this.el.classList.add(this.options['bottomClass']);
} else {
this.el.classList.remove(this.options['bottomClass']);
}
};
proto.recalc = function(){
//console.group('recalc:' + this.el.dataset['stickyId'])
//element to mimic visual properties from
var measureEl = (this.isTop ? this.el : this.stub);
//update stub content
this.stub.innerHTML = this.el.innerHTML;
cleanNode(this.stub);
//update parent container size & offsets
this.parentBox = getOffset(this.parent);
//update self size & position
this.height = this.el.offsetHeight;
var mStyle = getComputedStyle(measureEl);
this.ml = ~~mStyle.marginLeft.slice(0,-2);
this.mr = ~~mStyle.marginRight.slice(0,-2);
this.mt = ~~mStyle.marginTop.slice(0,-2);
this.mb = ~~mStyle.marginBottom.slice(0,-2);
this.scrollOffset = 0;
//update restrictions
this.restrictBox = this.getRestrictBox(this.within, measureEl);
//make restriction up to next sibling within one container
var prevSticky;
this.offset.bottom = 0;
this.offset.top = 0;
if (this.stack.length){
for (var i = this.stack.length; i--;){
if (prevSticky = Sticky.stack[this.stack[i]][this.stackId[i] - 1]){
//make offsets for stacked mode
var prevMeasurer = (prevSticky.isTop ? prevSticky.el : prevSticky.stub);
this.offset.top = prevSticky.offset.top + prevSticky.options.offset;
if (!(this.options['collapse'] && !isOverlap(measureEl, prevMeasurer))) {
this.offset.top += prevSticky.height + Math.max(prevSticky.mt, prevSticky.mb)//collapsed margin
var nextSticky = Sticky.stack[this.stack[i]][this.stackId[i]];
//multistacking-way of correcting bottom offsets
for( var j = this.stackId[i] - 1; (prevSticky = Sticky.stack[this.stack[i]][j]); j--){
prevSticky.offset.bottom = Math.max(prevSticky.offset.bottom, nextSticky.offset.bottom + nextSticky.height + nextSticky.mt + nextSticky.mb);
nextSticky = prevSticky;
}
}
}
//track stack heights;
Sticky.stackHeights[this.stack[i]] = this.offset.top + this.height + this.mt + this.mb;
}
} else if (prevSticky = Sticky.noStack[this.stackId[0] - 1]){
prevSticky.restrictBox.bottom = this.restrictBox.top - this.mt;
}
clearTimeout(this._updTimeout);
this._updTimeout = setTimeout(this.adjustSizeAndPosition, 0);
};
/**
* return box with sizes based on any restrictwithin object passed
*/
proto.getRestrictBox = function(within, measureEl){
var restrictBox = {
top: 0,
bottom: 0
};
if (within instanceof Element){
var offsetRect = getOffset(within)
restrictBox.top = Math.max(offsetRect.top, getOffset(measureEl).top);
//console.log(getOffset(this.stub))
restrictBox.bottom = within.offsetHeight + offsetRect.top;
} else if (within instanceof Object) {
if (within.top instanceof Element) {
var offsetRect = getOffset(within.top)
restrictBox.top = Math.max(offsetRect.top, getOffset(measureEl).top);
} else {
restrictBox.top = within.top;
}
if (within.bottom instanceof Element) {
var offsetRect = getOffset(within.bottom)
restrictBox.bottom = within.bottom.offsetHeight + offsetRect.top;
//console.log(offsetRect)
} else {
restrictBox.bottom = within.bottom;
}
} else {
//case of parent container
restrictBox.top = getOffset(measureEl).top;
restrictBox.bottom = this.parentBox.height + this.parentBox.top;
}
//console.log('Restrictbox', restrictBox)
return restrictBox;
};
proto.adjustSizeAndPosition = function(){
if (this.isTop){
this.el.style.cssText = this.initialStyle;
} else if (this.isBottom){
this.makeParkedBottomStyle();
} else {
this.makeStickedStyle();
}
this.check();
};
/** removes iframe, objects etc shit */
var badTags = ['object', 'iframe', 'embed', 'img'];
function cleanNode(node){
node.removeAttribute('id');
var idTags = node.querySelectorAll('[id]');
for (var k = 0; k < idTags.length; k++){
idTags[k].removeAttribute('id'); //avoid any uniqueness
idTags[k].removeAttribute('name'); //avoid any uniqueness
}
for (var i = 0; i < badTags.length; i++){
var tags = node.querySelectorAll(badTags[i]);
for (var j = tags.length; j--; ){
if (tags[j].tagName === 'SCRIPT') tags[j].parentNode.replaceChild(tags[j])
tags[j].removeAttribute('src');
tags[j].removeAttribute('href');
tags[j].removeAttribute('rel');
tags[j].removeAttribute('srcdoc');
}
}
}
var directions = ['left', 'top', 'right', 'bottom'],
mimicProperties = ['padding-', 'border-'];
/** copies size-related style of stub */
function mimicStyle(to, from){
var stubStyle = getComputedStyle(from),
stubOffset = getOffset(from),
pl = 0, pr = 0, ml = 0;
if (stubStyle['box-sizing'] !== 'border-box'){
pl = ~~stubStyle.paddingLeft.slice(0,-2)
pr = ~~stubStyle.paddingRight.slice(0,-2)
}
to.style.width = (stubOffset.width - pl - pr) + 'px';
to.style.left = stubOffset.left + 'px';
to.style.marginLeft = 0;
for (var i = 0; i < mimicProperties.length; i++){
for (var j = 0; j < directions.length; j++){
var prop = mimicProperties[i] + directions[j];
to.style[prop] = stubStyle[prop];
}
}
}
/** checks overlapping widths */
function isOverlap(left, right){
var lLeft = left.offsetLeft,
lRight = left.offsetLeft + left.offsetWidth,
rLeft = right.offsetLeft,
rRight = right.offsetWidth + right.offsetLeft;
if (lRight < rLeft && lLeft < rLeft
|| lRight > rRight && lLeft > rRight){
return false;
}
return true;
}
function getOffse | let rect = el.getBoundingClientRect()
//whether element is or is in fixed
var fixed = isFixed(el);
var xOffset = fixed ? 0 : window.pageXOffset;
var yOffset = fixed ? 0 : window.pageYOffset;
return {
left: rect.left + xOffset,
top: rect.top + yOffset,
width: rect.width,
height: rect.height
};
}
function isFixed (el) {
var parentEl = el;
//window is fixed, btw
if (el === window) return true;
//unlike the doc
if (el === document) return false;
while (parentEl) {
if (getComputedStyle(parentEl).position === 'fixed') return true;
parentEl = parentEl.offsetParent;
}
return false;
}
| t(el) {
| identifier_name |
index.js | var on = require('emmy/on');
var off = require('emmy/off');
module.exports = Sticky;
/**
* @constructor
*/
function Sticky(el, options) |
//list of instances
Sticky.list = [];
//mutually exclusive items
Sticky.noStack = [];
//stacks of items
Sticky.stack = {};
//heights of stacks
Sticky.stackHeights = {};
/** Update all sticky instances */
Sticky.recalc = function () {
Sticky.list.forEach(function (instance) {
instance.recalc();
});
};
/** API events */
on(document, 'sticky:recalc', Sticky.recalc);
var proto = Sticky.prototype;
proto.options = {
'offset': 0,
'within': null, //element or bounding box
'stubClass': 'sticky-stub',
'stickyClass': 'is-stuck',
'bottomClass': 'is-bottom',
'topClass': 'is-top',
'stack': null,
'collapse': true,
'recalcInterval': 20
};
/** when element removed or made hidden. */
proto.disable = function(){
if (this.stub.parentNode) this.parent.removeChild(this.stub);
this.unbindEvents();
this.isDisabled = true;
Sticky.recalc();
};
/** enables previously disabled element */
proto.enable = function(){
if (!this.stub.parentNode) this.parent.insertBefore(this.stub, this.el);
this.isDisabled = false;
this.bindEvents();
Sticky.recalc();
};
proto.bindEvents = function(){
on(document, 'scroll', this.check);
on(window, 'resize', this.recalc);
on(this.el, 'mouseover', this.observeStackScroll);
on(this.el, 'mouseout', this.stopObservingStackScroll);
};
proto.unbindEvents = function(){
off(document, 'scroll', this.check);
off(window, 'resize', this.recalc);
off(this.el, 'mouseover', this.observeStackScroll);
off(this.el, 'mouseout', this.stopObservingStackScroll);
};
/** changing state necessity checker */
proto.check = function(){
var vpTop = window.pageYOffset || document.documentElement.scrollTop;
//console.log('check:' + this.el.dataset['stickyId'], 'isFixed:' + this.isFixed, this.restrictBox)
if (this.isFixed){
if (!this.isTop && vpTop + this.offset.top + this.options.offset + this.height + this.mt + this.mb + this.scrollOffset >= this.restrictBox.bottom - this.offset.bottom){
//check bottom parking needed
this.parkBottom();
}
if (!this.isBottom && vpTop + this.offset.top + this.options.offset + this.mt + this.scrollOffset <= this.restrictBox.top){
//check top parking needed
this.parkTop();
}
} else {
if (this.isTop || this.isBottom){
if (vpTop + this.offset.top + this.options.offset + this.mt > this.restrictBox.top){
//fringe violation from top
if (vpTop + this.offset.top + this.options.offset + this.height + this.mt + this.mb < this.restrictBox.bottom - this.offset.bottom){
//fringe violation from top or bottom to the sticking zone
this.stick();
} else if (!this.isBottom) {
//fringe violation from top lower than bottom
this.stick();
this.parkBottom();
}
} else if(this.isBottom){
//fringe violation from bottom to higher than top
this.stick();
this.parkTop();
}
}
}
};
/**
* sticking inner routines
* when park top needed
*/
proto.parkTop = function(){
//this.el = this.parent.removeChild(this.el);
this.el.style.cssText = this.initialStyle;
//this.stub = this.parent.replaceChild(this.el, this.stub);
this.stub.style.display = 'none';
this.scrollOffset = 0;
this.isFixed = false;
this.isTop = true;
this.isBottom = false;
this.updateClasses();
this.isStackParked = true;
// console.log('parkTop', this.id)
};
/** when stop needed somewhere in between top and bottom */
proto.park = function(){
// console.log('parkMiddle', this.id)
this.isFixed = false;
this.isTop = false;
this.isBottom = false;
this.updateClasses();
this.isStackParked = true;
var offset = (window.pageYOffset || document.documentElement.scrollTop) + this.offset.top - this.parentBox.top + this.scrollOffset;
this.makeParkedStyle(offset);
};
/**
* to make fixed
* enhanced replace: faked visual stub is fastly replaced with natural one
*/
proto.stick = function(){
//this.el = this.parent.replaceChild(this.stub, this.el);
this.stub.style.display = this.initialDisplay;
this.makeStickedStyle();
//this.parent.insertBefore(this.el, this.stub);
this.isFixed = true;
this.isTop = false;
this.isBottom = false;
this.updateClasses();
this.isStackParked = false;
// console.log('stick', this.id)
};
/** when bottom land needed */
proto.parkBottom = function(){
this.makeParkedBottomStyle();
this.scrollOffset = 0;
this.isFixed = false;
this.isBottom = true;
this.isTop = false;
this.updateClasses();
this.isStackParked = true;
// console.log('parkBottom', this.id)
};
/**
* park all items within stack passed/all stacks of this
* used when item was scrolled on
*/
proto.parkStack = function(){
var stack = Sticky.stack[this.stack[0]];
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.park();
}
};
/** unpark all items of stack passed */
proto.stickStack = function(){
var stack = Sticky.stack[this.stack[0]]
var first = stack[0], last = stack[stack.length - 1];
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.stick();
}
};
/**
* begin observing scroll to park stack
*/
proto.observeStackScroll = function(){
var stack = Sticky.stack[this.stack[0]]
if (!stack) return;
var first = stack[0], last = stack[stack.length - 1];
//if stack is parked top or parked bottom - ignore
if (first.isTop || last.isTop) return;
//if stack isn’t higher than window height - ignore
if (Sticky.stackHeights[this.stack[0]] <= window.innerHeight && this.scrollOffset >= 0) return;
//capture stack’s scroll
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop) + this.scrollOffset;
on(document, 'scroll', this.captureScrollOffset);
return this;
};
/** stop observing scroll */
proto.stopObservingStackScroll = function(){
var stack = Sticky.stack[this.stack[0]];
if (!stack) return;
var last = stack[stack.length-1], first = stack[0];
off(document, 'scroll', this.captureScrollOffset);
if (first.isTop || first.isBottom || last.isTop || last.isBottom) {
return;
}
if (this.isStackParked) this.stickStack();
};
/** when item was scrolled on - capture how much it is scrolled */
proto.captureScrollOffset = function(e){
var scrollOffset = this.scrollStartOffset - (window.pageYOffset || document.documentElement.scrollTop);
var stack = Sticky.stack[this.stack[0]];
var last = stack[stack.length-1], first = stack[0];
//ignore outside sticking
if (first.isTop || first.isBottom || last.isTop || last.isBottom) {
return;
}
var stickNeeded = false, parkNeeded = false;
//if bottom is higher or equal than viewport’s bottom - stick within viewport
if ( scrollOffset < window.innerHeight - (Sticky.stackHeights[this.stack[0]]) ){
scrollOffset = window.innerHeight - (Sticky.stackHeights[this.stack[0]]);
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop) + scrollOffset;
stickNeeded = true;
}
//if top is lower or equal to the viewport’s top - stick within viewport
else if ( scrollOffset > 0){
scrollOffset = 0;
this.scrollStartOffset = (window.pageYOffset || document.documentElement.scrollTop);
stickNeeded = true;
}
//if stack items is somewhere in between
else if (!this.isStackParked ){
parkNeeded = true;
}
for (var i = 0; i < stack.length; i++){
var item = stack[i]
item.scrollOffset = scrollOffset
}
if (stickNeeded && this.isStackParked) return this.stickStack();
else if (parkNeeded && !this.isStackParked) return this.parkStack();
};
/** set up style of element as if it is parked somewhere / at the bottom */
proto.makeParkedStyle = function(top){
this.el.style.cssText = this.initialStyle;
this.el.style.position = 'absolute';
this.el.style.top = top + 'px';
mimicStyle(this.el, this.stub);
this.el.style.left = this.stub.offsetLeft + 'px';
};
proto.makeParkedBottomStyle = function(){
this.makeParkedStyle(this.restrictBox.bottom - this.offset.bottom - this.parentBox.top - this.height - this.mt - this.mb);
};
proto.makeStickedStyle = function(){
this.el.style.cssText = this.initialStyle;
this.el.style.position = 'fixed';
this.el.style.top = this.offset.top + this.options.offset + this.scrollOffset + 'px';
mimicStyle(this.el, this.stub);
};
//makes element classes reflecting it's state (this.isTop, this.isBottom, this.isFixed)
proto.updateClasses = function(){
if (this.isTop){
this.el.classList.add(this.options['topClass']);
} else {
this.el.classList.remove(this.options['topClass']);
}
if (this.isFixed){
this.el.classList.add(this.options['stickyClass']);
} else {
this.el.classList.remove(this.options['stickyClass']);
}
if (this.isBottom){
this.el.classList.add(this.options['bottomClass']);
} else {
this.el.classList.remove(this.options['bottomClass']);
}
};
proto.recalc = function(){
//console.group('recalc:' + this.el.dataset['stickyId'])
//element to mimic visual properties from
var measureEl = (this.isTop ? this.el : this.stub);
//update stub content
this.stub.innerHTML = this.el.innerHTML;
cleanNode(this.stub);
//update parent container size & offsets
this.parentBox = getOffset(this.parent);
//update self size & position
this.height = this.el.offsetHeight;
var mStyle = getComputedStyle(measureEl);
this.ml = ~~mStyle.marginLeft.slice(0,-2);
this.mr = ~~mStyle.marginRight.slice(0,-2);
this.mt = ~~mStyle.marginTop.slice(0,-2);
this.mb = ~~mStyle.marginBottom.slice(0,-2);
this.scrollOffset = 0;
//update restrictions
this.restrictBox = this.getRestrictBox(this.within, measureEl);
//make restriction up to next sibling within one container
var prevSticky;
this.offset.bottom = 0;
this.offset.top = 0;
if (this.stack.length){
for (var i = this.stack.length; i--;){
if (prevSticky = Sticky.stack[this.stack[i]][this.stackId[i] - 1]){
//make offsets for stacked mode
var prevMeasurer = (prevSticky.isTop ? prevSticky.el : prevSticky.stub);
this.offset.top = prevSticky.offset.top + prevSticky.options.offset;
if (!(this.options['collapse'] && !isOverlap(measureEl, prevMeasurer))) {
this.offset.top += prevSticky.height + Math.max(prevSticky.mt, prevSticky.mb)//collapsed margin
var nextSticky = Sticky.stack[this.stack[i]][this.stackId[i]];
//multistacking-way of correcting bottom offsets
for( var j = this.stackId[i] - 1; (prevSticky = Sticky.stack[this.stack[i]][j]); j--){
prevSticky.offset.bottom = Math.max(prevSticky.offset.bottom, nextSticky.offset.bottom + nextSticky.height + nextSticky.mt + nextSticky.mb);
nextSticky = prevSticky;
}
}
}
//track stack heights;
Sticky.stackHeights[this.stack[i]] = this.offset.top + this.height + this.mt + this.mb;
}
} else if (prevSticky = Sticky.noStack[this.stackId[0] - 1]){
prevSticky.restrictBox.bottom = this.restrictBox.top - this.mt;
}
clearTimeout(this._updTimeout);
this._updTimeout = setTimeout(this.adjustSizeAndPosition, 0);
};
/**
* return box with sizes based on any restrictwithin object passed
*/
proto.getRestrictBox = function(within, measureEl){
var restrictBox = {
top: 0,
bottom: 0
};
if (within instanceof Element){
var offsetRect = getOffset(within)
restrictBox.top = Math.max(offsetRect.top, getOffset(measureEl).top);
//console.log(getOffset(this.stub))
restrictBox.bottom = within.offsetHeight + offsetRect.top;
} else if (within instanceof Object) {
if (within.top instanceof Element) {
var offsetRect = getOffset(within.top)
restrictBox.top = Math.max(offsetRect.top, getOffset(measureEl).top);
} else {
restrictBox.top = within.top;
}
if (within.bottom instanceof Element) {
var offsetRect = getOffset(within.bottom)
restrictBox.bottom = within.bottom.offsetHeight + offsetRect.top;
//console.log(offsetRect)
} else {
restrictBox.bottom = within.bottom;
}
} else {
//case of parent container
restrictBox.top = getOffset(measureEl).top;
restrictBox.bottom = this.parentBox.height + this.parentBox.top;
}
//console.log('Restrictbox', restrictBox)
return restrictBox;
};
proto.adjustSizeAndPosition = function(){
if (this.isTop){
this.el.style.cssText = this.initialStyle;
} else if (this.isBottom){
this.makeParkedBottomStyle();
} else {
this.makeStickedStyle();
}
this.check();
};
/** removes iframe, objects etc shit */
var badTags = ['object', 'iframe', 'embed', 'img'];
function cleanNode(node){
node.removeAttribute('id');
var idTags = node.querySelectorAll('[id]');
for (var k = 0; k < idTags.length; k++){
idTags[k].removeAttribute('id'); //avoid any uniqueness
idTags[k].removeAttribute('name'); //avoid any uniqueness
}
for (var i = 0; i < badTags.length; i++){
var tags = node.querySelectorAll(badTags[i]);
for (var j = tags.length; j--; ){
if (tags[j].tagName === 'SCRIPT') tags[j].parentNode.replaceChild(tags[j])
tags[j].removeAttribute('src');
tags[j].removeAttribute('href');
tags[j].removeAttribute('rel');
tags[j].removeAttribute('srcdoc');
}
}
}
var directions = ['left', 'top', 'right', 'bottom'],
mimicProperties = ['padding-', 'border-'];
/** copies size-related style of stub */
function mimicStyle(to, from){
var stubStyle = getComputedStyle(from),
stubOffset = getOffset(from),
pl = 0, pr = 0, ml = 0;
if (stubStyle['box-sizing'] !== 'border-box'){
pl = ~~stubStyle.paddingLeft.slice(0,-2)
pr = ~~stubStyle.paddingRight.slice(0,-2)
}
to.style.width = (stubOffset.width - pl - pr) + 'px';
to.style.left = stubOffset.left + 'px';
to.style.marginLeft = 0;
for (var i = 0; i < mimicProperties.length; i++){
for (var j = 0; j < directions.length; j++){
var prop = mimicProperties[i] + directions[j];
to.style[prop] = stubStyle[prop];
}
}
}
/** checks overlapping widths */
function isOverlap(left, right){
var lLeft = left.offsetLeft,
lRight = left.offsetLeft + left.offsetWidth,
rLeft = right.offsetLeft,
rRight = right.offsetWidth + right.offsetLeft;
if (lRight < rLeft && lLeft < rLeft
|| lRight > rRight && lLeft > rRight){
return false;
}
return true;
}
function getOffset(el) {
let rect = el.getBoundingClientRect()
//whether element is or is in fixed
var fixed = isFixed(el);
var xOffset = fixed ? 0 : window.pageXOffset;
var yOffset = fixed ? 0 : window.pageYOffset;
return {
left: rect.left + xOffset,
top: rect.top + yOffset,
width: rect.width,
height: rect.height
};
}
function isFixed (el) {
var parentEl = el;
//window is fixed, btw
if (el === window) return true;
//unlike the doc
if (el === document) return false;
while (parentEl) {
if (getComputedStyle(parentEl).position === 'fixed') return true;
parentEl = parentEl.offsetParent;
}
return false;
}
| {
if (el.getAttribute('data-sticky-id') === undefined) {
return console.log('Sticky already exist');
}
this.el = el;
this.parent = this.el.parentNode;
//recognize attributes
var dataset = el.dataset;
if (!dataset){
dataset = {};
if (el.getAttribute('data-within')) dataset['within'] = el.getAttribute('data-within');
if (el.getAttribute('data-offset')) dataset['offset'] = el.getAttribute('data-offset');
if (el.getAttribute('data-stack')) dataset['stack'] = el.getAttribute('data-stack');
if (el.getAttribute('data-sticky-class')) dataset['stickyClass'] = el.getAttribute('data-sticky-class');
}
this.options = Object.assign({}, this.options, dataset, options);
//query selector, if passed one
if ( typeof this.options['within'] === 'string' && this.options['within'].trim() ){
this.within = document.body.querySelector(this.options['within']);
} else {
this.within = this.options['within'];
}
//keep list
this.el.setAttribute('data-sticky-id', Sticky.list.length);
this.id = Sticky.list.length;
Sticky.list.push(this);
//state
this.isFixed = false;
this.isBottom = false;
this.isTop = true;
this.updateClasses();
//boundaries to strict within
this.restrictBox = {
top: 0,
bottom: 9999
};
//self position & size
this.height = 0;
this.isDisabled = false;
//parent position & size
this.parentBox = {
top: 0,
height: 0
}
//mind gap from bottom & top in addition to restrictBox (for stacks)
this.options.offset = parseFloat(this.options['offset']) || 0;
this.offset = {
top: 0,
bottom: 0
};
//additional gap if item being scrolled
this.scrollOffset = 0;
//Detect whether stacking is needed
var prevEl = this.el;
this.stackId = [];
this.stack = [];
if (this.options['stack']) {
var stack = this.options['stack'].split(',');
for (var i = stack.length; i--;){
stack[i] = stack[i].trim();
if (!Sticky.stack[stack[i]]) Sticky.stack[stack[i]] = [];
this.stackId[i] = Sticky.stack[stack[i]].length;
this.stack.push(stack[i]);
Sticky.stack[stack[i]].push(this)
}
} else {
this.stackId[0] = Sticky.noStack.length;
Sticky.noStack.push(this);
}
//stub is a spacer filling space when element is stuck
this.stub = this.el.cloneNode();
this.stub.classList.add(this.options['stubClass']);
this.stub.style.visibility = 'hidden';
this.stub.style.display = 'none';
this.stub.removeAttribute('hidden');
//save initial inline style
this.initialStyle = this.el.style.cssText;
this.initialDisplay = getComputedStyle(this.el)['display'];
//ensure parent's container relative coordinates
var pStyle = getComputedStyle(this.parent);
if (pStyle.position == 'static') this.parent.style.position = 'relative';
//bind methods
this.check = this.check.bind(this);
this.recalc = this.recalc.bind(this);
this.disable = this.disable.bind(this);
this.enable = this.enable.bind(this);
this.bindEvents = this.bindEvents.bind(this);
this.adjustSizeAndPosition = this.adjustSizeAndPosition.bind(this);
this.park = this.park.bind(this);
this.stick = this.stick.bind(this);
this.parkStack = this.parkStack.bind(this);
this.stickStack = this.stickStack.bind(this);
this.captureScrollOffset = this.captureScrollOffset.bind(this);
this.observeStackScroll = this.observeStackScroll.bind(this);
this.stopObservingStackScroll = this.stopObservingStackScroll.bind(this);
if (this.initialDisplay === 'none') {
this.initialDisplay = 'block';
this.disable();
}
else this.enable();
} | identifier_body |
keybindingsRegistry.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 {BinaryKeybindings, KeyCode} from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
import {TypeConstraint, validateConstraints} from 'vs/base/common/types';
import {ICommandHandler, ICommandHandlerDescription, ICommandsMap, IKeybindingItem, IKeybindings, KbExpr} from 'vs/platform/keybinding/common/keybindingService';
import {Registry} from 'vs/platform/platform';
export interface ICommandRule extends IKeybindings {
id: string;
weight: number;
context: KbExpr;
}
export interface ICommandDescriptor extends ICommandRule {
handler: ICommandHandler;
description?: string | ICommandHandlerDescription;
}
export interface IKeybindingsRegistry {
registerCommandRule(rule: ICommandRule);
registerCommandDesc(desc: ICommandDescriptor): void;
getCommands(): ICommandsMap;
getDefaultKeybindings(): IKeybindingItem[];
WEIGHT: {
editorCore(importance?: number): number;
editorContrib(importance?: number): number;
workbenchContrib(importance?: number): number;
builtinExtension(importance?: number): number;
externalExtension(importance?: number): number;
};
}
class KeybindingsRegistryImpl implements IKeybindingsRegistry {
private _keybindings: IKeybindingItem[];
private _commands: ICommandsMap;
public WEIGHT = {
editorCore: (importance: number = 0): number => {
return 0 + importance;
},
editorContrib: (importance: number = 0): number => {
return 100 + importance;
},
workbenchContrib: (importance: number = 0): number => {
return 200 + importance;
},
builtinExtension: (importance: number = 0): number => {
return 300 + importance;
},
externalExtension: (importance: number = 0): number => {
return 400 + importance;
}
};
constructor() {
this._keybindings = [];
this._commands = Object.create(null);
}
/**
* Take current platform into account and reduce to primary & secondary.
*/
private static bindToCurrentPlatform(kb: IKeybindings): { primary?: number; secondary?: number[]; } {
if (platform.isWindows) {
if (kb && kb.win) {
return kb.win;
}
} else if (platform.isMacintosh) {
if (kb && kb.mac) {
return kb.mac;
}
} else |
return kb;
}
public registerCommandRule(rule: ICommandRule): void {
let actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
if (actualKb && actualKb.primary) {
this.registerDefaultKeybinding(actualKb.primary, rule.id, rule.weight, 0, rule.context);
}
if (actualKb && Array.isArray(actualKb.secondary)) {
actualKb.secondary.forEach((k, i) => this.registerDefaultKeybinding(k, rule.id, rule.weight, -i - 1, rule.context));
}
}
public registerCommandDesc(desc: ICommandDescriptor): void {
this.registerCommandRule(desc);
// if (_commands[desc.id]) {
// console.warn('Duplicate handler for command: ' + desc.id);
// }
// this._commands[desc.id] = desc.handler;
let handler = desc.handler;
let description = desc.description || handler.description;
// add argument validation if rich command metadata is provided
if (typeof description === 'object') {
let constraints: TypeConstraint[] = [];
for (let arg of description.args) {
constraints.push(arg.constraint);
}
handler = function(accesor, args) {
validateConstraints(args, constraints);
return desc.handler(accesor, args);
};
}
// make sure description is there
handler.description = description;
// register handler
this._commands[desc.id] = handler;
}
public getCommands(): ICommandsMap {
return this._commands;
}
private registerDefaultKeybinding(keybinding: number, commandId: string, weight1: number, weight2: number, context: KbExpr): void {
if (platform.isWindows) {
if (BinaryKeybindings.hasCtrlCmd(keybinding) && !BinaryKeybindings.hasShift(keybinding) && BinaryKeybindings.hasAlt(keybinding) && !BinaryKeybindings.hasWinCtrl(keybinding)) {
if (/^[A-Z0-9\[\]\|\;\'\,\.\/\`]$/.test(KeyCode.toString(BinaryKeybindings.extractKeyCode(keybinding)))) {
console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId);
}
}
}
this._keybindings.push({
keybinding: keybinding,
command: commandId,
context: context,
weight1: weight1,
weight2: weight2
});
}
public getDefaultKeybindings(): IKeybindingItem[] {
return this._keybindings;
}
}
export let KeybindingsRegistry: IKeybindingsRegistry = new KeybindingsRegistryImpl();
// Define extension point ids
export let Extensions = {
EditorModes: 'platform.keybindingsRegistry'
};
Registry.add(Extensions.EditorModes, KeybindingsRegistry); | {
if (kb && kb.linux) {
return kb.linux;
}
} | conditional_block |
keybindingsRegistry.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 {BinaryKeybindings, KeyCode} from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
import {TypeConstraint, validateConstraints} from 'vs/base/common/types';
import {ICommandHandler, ICommandHandlerDescription, ICommandsMap, IKeybindingItem, IKeybindings, KbExpr} from 'vs/platform/keybinding/common/keybindingService';
import {Registry} from 'vs/platform/platform';
export interface ICommandRule extends IKeybindings {
id: string;
weight: number;
context: KbExpr;
}
export interface ICommandDescriptor extends ICommandRule {
handler: ICommandHandler;
description?: string | ICommandHandlerDescription;
}
export interface IKeybindingsRegistry {
registerCommandRule(rule: ICommandRule);
registerCommandDesc(desc: ICommandDescriptor): void;
getCommands(): ICommandsMap;
getDefaultKeybindings(): IKeybindingItem[];
WEIGHT: {
editorCore(importance?: number): number;
editorContrib(importance?: number): number;
workbenchContrib(importance?: number): number;
builtinExtension(importance?: number): number;
externalExtension(importance?: number): number;
};
}
class KeybindingsRegistryImpl implements IKeybindingsRegistry {
private _keybindings: IKeybindingItem[];
private _commands: ICommandsMap;
public WEIGHT = {
editorCore: (importance: number = 0): number => {
return 0 + importance;
},
editorContrib: (importance: number = 0): number => {
return 100 + importance;
},
workbenchContrib: (importance: number = 0): number => {
return 200 + importance;
},
builtinExtension: (importance: number = 0): number => {
return 300 + importance;
},
externalExtension: (importance: number = 0): number => {
return 400 + importance;
}
};
constructor() |
/**
* Take current platform into account and reduce to primary & secondary.
*/
private static bindToCurrentPlatform(kb: IKeybindings): { primary?: number; secondary?: number[]; } {
if (platform.isWindows) {
if (kb && kb.win) {
return kb.win;
}
} else if (platform.isMacintosh) {
if (kb && kb.mac) {
return kb.mac;
}
} else {
if (kb && kb.linux) {
return kb.linux;
}
}
return kb;
}
public registerCommandRule(rule: ICommandRule): void {
let actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
if (actualKb && actualKb.primary) {
this.registerDefaultKeybinding(actualKb.primary, rule.id, rule.weight, 0, rule.context);
}
if (actualKb && Array.isArray(actualKb.secondary)) {
actualKb.secondary.forEach((k, i) => this.registerDefaultKeybinding(k, rule.id, rule.weight, -i - 1, rule.context));
}
}
public registerCommandDesc(desc: ICommandDescriptor): void {
this.registerCommandRule(desc);
// if (_commands[desc.id]) {
// console.warn('Duplicate handler for command: ' + desc.id);
// }
// this._commands[desc.id] = desc.handler;
let handler = desc.handler;
let description = desc.description || handler.description;
// add argument validation if rich command metadata is provided
if (typeof description === 'object') {
let constraints: TypeConstraint[] = [];
for (let arg of description.args) {
constraints.push(arg.constraint);
}
handler = function(accesor, args) {
validateConstraints(args, constraints);
return desc.handler(accesor, args);
};
}
// make sure description is there
handler.description = description;
// register handler
this._commands[desc.id] = handler;
}
public getCommands(): ICommandsMap {
return this._commands;
}
private registerDefaultKeybinding(keybinding: number, commandId: string, weight1: number, weight2: number, context: KbExpr): void {
if (platform.isWindows) {
if (BinaryKeybindings.hasCtrlCmd(keybinding) && !BinaryKeybindings.hasShift(keybinding) && BinaryKeybindings.hasAlt(keybinding) && !BinaryKeybindings.hasWinCtrl(keybinding)) {
if (/^[A-Z0-9\[\]\|\;\'\,\.\/\`]$/.test(KeyCode.toString(BinaryKeybindings.extractKeyCode(keybinding)))) {
console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId);
}
}
}
this._keybindings.push({
keybinding: keybinding,
command: commandId,
context: context,
weight1: weight1,
weight2: weight2
});
}
public getDefaultKeybindings(): IKeybindingItem[] {
return this._keybindings;
}
}
export let KeybindingsRegistry: IKeybindingsRegistry = new KeybindingsRegistryImpl();
// Define extension point ids
export let Extensions = {
EditorModes: 'platform.keybindingsRegistry'
};
Registry.add(Extensions.EditorModes, KeybindingsRegistry); | {
this._keybindings = [];
this._commands = Object.create(null);
} | identifier_body |
keybindingsRegistry.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 {BinaryKeybindings, KeyCode} from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
import {TypeConstraint, validateConstraints} from 'vs/base/common/types';
import {ICommandHandler, ICommandHandlerDescription, ICommandsMap, IKeybindingItem, IKeybindings, KbExpr} from 'vs/platform/keybinding/common/keybindingService';
import {Registry} from 'vs/platform/platform';
export interface ICommandRule extends IKeybindings {
id: string;
weight: number;
context: KbExpr;
}
export interface ICommandDescriptor extends ICommandRule {
handler: ICommandHandler;
description?: string | ICommandHandlerDescription;
}
export interface IKeybindingsRegistry {
registerCommandRule(rule: ICommandRule);
registerCommandDesc(desc: ICommandDescriptor): void;
getCommands(): ICommandsMap;
getDefaultKeybindings(): IKeybindingItem[];
WEIGHT: {
editorCore(importance?: number): number;
editorContrib(importance?: number): number;
workbenchContrib(importance?: number): number;
builtinExtension(importance?: number): number;
externalExtension(importance?: number): number;
};
}
class KeybindingsRegistryImpl implements IKeybindingsRegistry {
private _keybindings: IKeybindingItem[];
private _commands: ICommandsMap;
public WEIGHT = {
editorCore: (importance: number = 0): number => {
return 0 + importance;
},
editorContrib: (importance: number = 0): number => {
return 100 + importance;
},
workbenchContrib: (importance: number = 0): number => {
return 200 + importance;
},
builtinExtension: (importance: number = 0): number => {
return 300 + importance;
},
externalExtension: (importance: number = 0): number => {
return 400 + importance;
}
};
constructor() {
this._keybindings = [];
this._commands = Object.create(null);
}
/**
* Take current platform into account and reduce to primary & secondary.
*/
private static bindToCurrentPlatform(kb: IKeybindings): { primary?: number; secondary?: number[]; } {
if (platform.isWindows) {
if (kb && kb.win) {
return kb.win;
}
} else if (platform.isMacintosh) {
if (kb && kb.mac) {
return kb.mac;
}
} else {
if (kb && kb.linux) {
return kb.linux;
}
}
return kb;
}
public registerCommandRule(rule: ICommandRule): void {
let actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
if (actualKb && actualKb.primary) {
this.registerDefaultKeybinding(actualKb.primary, rule.id, rule.weight, 0, rule.context);
}
if (actualKb && Array.isArray(actualKb.secondary)) {
actualKb.secondary.forEach((k, i) => this.registerDefaultKeybinding(k, rule.id, rule.weight, -i - 1, rule.context));
}
}
public registerCommandDesc(desc: ICommandDescriptor): void {
this.registerCommandRule(desc);
// if (_commands[desc.id]) {
// console.warn('Duplicate handler for command: ' + desc.id);
// }
// this._commands[desc.id] = desc.handler;
let handler = desc.handler;
let description = desc.description || handler.description;
// add argument validation if rich command metadata is provided
if (typeof description === 'object') {
let constraints: TypeConstraint[] = [];
for (let arg of description.args) {
constraints.push(arg.constraint);
}
handler = function(accesor, args) {
validateConstraints(args, constraints);
return desc.handler(accesor, args);
};
}
// make sure description is there
handler.description = description;
// register handler
this._commands[desc.id] = handler;
}
public getCommands(): ICommandsMap {
return this._commands;
}
private | (keybinding: number, commandId: string, weight1: number, weight2: number, context: KbExpr): void {
if (platform.isWindows) {
if (BinaryKeybindings.hasCtrlCmd(keybinding) && !BinaryKeybindings.hasShift(keybinding) && BinaryKeybindings.hasAlt(keybinding) && !BinaryKeybindings.hasWinCtrl(keybinding)) {
if (/^[A-Z0-9\[\]\|\;\'\,\.\/\`]$/.test(KeyCode.toString(BinaryKeybindings.extractKeyCode(keybinding)))) {
console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId);
}
}
}
this._keybindings.push({
keybinding: keybinding,
command: commandId,
context: context,
weight1: weight1,
weight2: weight2
});
}
public getDefaultKeybindings(): IKeybindingItem[] {
return this._keybindings;
}
}
export let KeybindingsRegistry: IKeybindingsRegistry = new KeybindingsRegistryImpl();
// Define extension point ids
export let Extensions = {
EditorModes: 'platform.keybindingsRegistry'
};
Registry.add(Extensions.EditorModes, KeybindingsRegistry); | registerDefaultKeybinding | identifier_name |
keybindingsRegistry.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 {BinaryKeybindings, KeyCode} from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
import {TypeConstraint, validateConstraints} from 'vs/base/common/types';
import {ICommandHandler, ICommandHandlerDescription, ICommandsMap, IKeybindingItem, IKeybindings, KbExpr} from 'vs/platform/keybinding/common/keybindingService';
import {Registry} from 'vs/platform/platform';
export interface ICommandRule extends IKeybindings {
id: string;
weight: number;
context: KbExpr;
}
export interface ICommandDescriptor extends ICommandRule {
handler: ICommandHandler;
description?: string | ICommandHandlerDescription;
}
export interface IKeybindingsRegistry {
registerCommandRule(rule: ICommandRule);
registerCommandDesc(desc: ICommandDescriptor): void;
getCommands(): ICommandsMap;
getDefaultKeybindings(): IKeybindingItem[];
WEIGHT: {
editorCore(importance?: number): number;
editorContrib(importance?: number): number;
workbenchContrib(importance?: number): number;
builtinExtension(importance?: number): number;
externalExtension(importance?: number): number;
};
}
class KeybindingsRegistryImpl implements IKeybindingsRegistry {
private _keybindings: IKeybindingItem[];
private _commands: ICommandsMap;
public WEIGHT = {
editorCore: (importance: number = 0): number => {
return 0 + importance;
},
editorContrib: (importance: number = 0): number => {
return 100 + importance;
},
workbenchContrib: (importance: number = 0): number => {
return 200 + importance;
},
builtinExtension: (importance: number = 0): number => {
return 300 + importance;
},
externalExtension: (importance: number = 0): number => {
return 400 + importance;
}
};
constructor() {
this._keybindings = [];
this._commands = Object.create(null);
}
/**
* Take current platform into account and reduce to primary & secondary.
*/
private static bindToCurrentPlatform(kb: IKeybindings): { primary?: number; secondary?: number[]; } {
if (platform.isWindows) {
if (kb && kb.win) {
return kb.win;
}
} else if (platform.isMacintosh) {
if (kb && kb.mac) {
return kb.mac;
}
} else {
if (kb && kb.linux) {
return kb.linux;
}
}
return kb;
}
public registerCommandRule(rule: ICommandRule): void {
let actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule);
if (actualKb && actualKb.primary) {
this.registerDefaultKeybinding(actualKb.primary, rule.id, rule.weight, 0, rule.context);
}
if (actualKb && Array.isArray(actualKb.secondary)) {
actualKb.secondary.forEach((k, i) => this.registerDefaultKeybinding(k, rule.id, rule.weight, -i - 1, rule.context));
}
}
public registerCommandDesc(desc: ICommandDescriptor): void {
this.registerCommandRule(desc);
// if (_commands[desc.id]) {
// console.warn('Duplicate handler for command: ' + desc.id);
// }
// this._commands[desc.id] = desc.handler;
let handler = desc.handler;
let description = desc.description || handler.description;
// add argument validation if rich command metadata is provided
if (typeof description === 'object') {
let constraints: TypeConstraint[] = [];
for (let arg of description.args) {
constraints.push(arg.constraint);
}
handler = function(accesor, args) {
validateConstraints(args, constraints);
return desc.handler(accesor, args);
};
}
// make sure description is there
handler.description = description;
// register handler
this._commands[desc.id] = handler;
}
public getCommands(): ICommandsMap {
return this._commands;
}
private registerDefaultKeybinding(keybinding: number, commandId: string, weight1: number, weight2: number, context: KbExpr): void {
if (platform.isWindows) {
if (BinaryKeybindings.hasCtrlCmd(keybinding) && !BinaryKeybindings.hasShift(keybinding) && BinaryKeybindings.hasAlt(keybinding) && !BinaryKeybindings.hasWinCtrl(keybinding)) {
if (/^[A-Z0-9\[\]\|\;\'\,\.\/\`]$/.test(KeyCode.toString(BinaryKeybindings.extractKeyCode(keybinding)))) {
console.warn('Ctrl+Alt+ keybindings should not be used by default under Windows. Offender: ', keybinding, ' for ', commandId);
}
}
}
this._keybindings.push({
keybinding: keybinding,
command: commandId,
context: context,
weight1: weight1,
weight2: weight2 | public getDefaultKeybindings(): IKeybindingItem[] {
return this._keybindings;
}
}
export let KeybindingsRegistry: IKeybindingsRegistry = new KeybindingsRegistryImpl();
// Define extension point ids
export let Extensions = {
EditorModes: 'platform.keybindingsRegistry'
};
Registry.add(Extensions.EditorModes, KeybindingsRegistry); | });
}
| random_line_split |
offset.js | define([
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* Gets a window from an element
*/
function | ( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
// Subtract offsetParent scroll positions
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) -
offsetParent.scrollTop();
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) -
offsetParent.scrollLeft();
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
return jQuery;
});
| getWindow | identifier_name |
offset.js | define([
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* Gets a window from an element
*/
function getWindow( elem ) |
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
// Subtract offsetParent scroll positions
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) -
offsetParent.scrollTop();
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) -
offsetParent.scrollLeft();
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
return jQuery;
});
| {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
} | identifier_body |
offset.js | define([
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) |
// Add offsetParent borders
// Subtract offsetParent scroll positions
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) -
offsetParent.scrollTop();
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) -
offsetParent.scrollLeft();
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
return jQuery;
});
| {
parentOffset = offsetParent.offset();
} | conditional_block |
offset.js | define([
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
}; | jQuery.fn.extend({
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
// Subtract offsetParent scroll positions
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) -
offsetParent.scrollTop();
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) -
offsetParent.scrollLeft();
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
return jQuery;
}); | random_line_split | |
mzasm.js | #!/usr/bin/env node
const NumberUtil = require("../js/lib/number-util.js");
var Z80_assemble = require('../js/Z80/assembler');
var MZ_TapeHeader = require('../js/lib/mz-tape-header');
var changeExt = require('../js/lib/change-ext.js');
var fs = require('fs');
var getPackageJson = require("./lib/get-package-json");
var npmInfo = getPackageJson(__dirname + "/..");
var Getopt = require('node-getopt');
var getopt = new Getopt([
['m', 'map=FILENAME', 'output map file name'],
['z', 'output-MZT-header', 'output MZT header'],
['a', 'loading-address=ADDR', 'set loading address'],
['e', 'execution-address=ADDR', 'set execution address'],
['t', 'reuse-mzt-header=FILENAME', "reuse the MZT header."],
['o', 'output-file=FILENAME', 'filename to output'],
['h', 'help', 'display this help'],
['v', 'version', 'show version']
]);
var cli = getopt.parseSystem();
var description = "A simple Z80 assembler -- " + npmInfo.name + "@" + npmInfo.version;
getopt.setHelp(
"Usage: mzasm [OPTION] filename [filename ...]\n" +
description + "\n" +
"\n" +
"[[OPTIONS]]\n" +
"\n" +
"Installation: npm install -g mz700-js\n" +
"Repository: https://github.com/takamin/mz700-js");
if(cli.options.help) {
getopt.showHelp();
process.exit(0);
}
if(cli.options.version) {
console.log(description);
process.exit(0);
}
var args = require("hash-arg").get(["input_filenames:string[]"], cli.argv);
if(cli.argv.length < 1) {
console.error('error: no input file');
process.exit(-1);
}
// Determine the output filename
var output_filename = null;
if('output-file' in cli.options) {
output_filename = cli.options['output-file'];
} else {
var ext = null;
if('reuse-mzt-header' in cli.options
|| 'output-MZT-header' in cli.options)
{
ext = ".mzt";
} else {
ext = ".bin";
}
let input_filename = args.input_filenames[0];
output_filename = changeExt(input_filename, ext);
}
// Determine filename of address map
var fnMap = null;
if('map' in cli.options) {
fnMap = cli.options['map'];
} else {
fnMap = changeExt(output_filename, ".map");
}
//
// MZT-Header
//
var mzt_header = null;
if('reuse-mzt-header' in cli.options) {
//
// Load MZT-Header from other MZT-File.
//
var mzt_filebuf = fs.readFileSync(cli.options['reuse-mzt-header']);
mzt_header = new MZ_TapeHeader(mzt_filebuf, 0);
} else if('output-MZT-header' in cli.options) |
(async function() {
let sources = [];
await Promise.all(args.input_filenames.map( input_filename => {
return new Promise( (resolve, reject) => {
fs.readFile(input_filename, 'utf-8', function(err, data) {
if(err) {
reject(err);
} else {
sources.push(data);
resolve(data);
}
});
});
}));
//
// Assemble
//
let asm = Z80_assemble.assemble(sources);
//
// Set binary size to MZT Header
//
var mzt_header_buf = [];
if(mzt_header != null) {
if(mzt_header.addrLoad == 0) {
mzt_header.setAddrLoad(asm.minAddr);
}
if(mzt_header.addrExec == 0) {
mzt_header.setAddrExec(asm.minAddr);
}
mzt_header.setFilesize(asm.buffer.length);
mzt_header_buf = mzt_header.buffer;
}
//
// Write out
//
fs.writeFileSync(
output_filename,
Buffer.from(mzt_header_buf.concat(asm.buffer)));
//
// Output address map
//
let map = Z80_assemble.hashMapArray(asm.label2value).map(function(item) {
return [item.label, ":\t", NumberUtil.HEX(item.address, 4), "H"].join('');
}).join("\n");
if(map.length > 0) {
fs.writeFileSync(fnMap, map);
}
}());
| {
//
// Create MZT-Header from the informations specified in command line options
//
var load_addr = 0;
var exec_addr = 0;
if('loading-address' in cli.options) {
load_addr = parseInt(cli.options['loading-address'], 0);
exec_addr = load_addr;
}
if('execution-address' in cli.options) {
exec_addr = parseInt(cli.options['execution-address'], 0);
}
mzt_header = MZ_TapeHeader.createNew();
mzt_header.setFilename(output_filename);
mzt_header.setAddrLoad(load_addr);
mzt_header.setAddrExec(exec_addr);
} | conditional_block |
mzasm.js | #!/usr/bin/env node
const NumberUtil = require("../js/lib/number-util.js");
var Z80_assemble = require('../js/Z80/assembler');
var MZ_TapeHeader = require('../js/lib/mz-tape-header');
var changeExt = require('../js/lib/change-ext.js');
var fs = require('fs');
var getPackageJson = require("./lib/get-package-json");
var npmInfo = getPackageJson(__dirname + "/..");
var Getopt = require('node-getopt');
var getopt = new Getopt([
['m', 'map=FILENAME', 'output map file name'],
['z', 'output-MZT-header', 'output MZT header'],
['a', 'loading-address=ADDR', 'set loading address'],
['e', 'execution-address=ADDR', 'set execution address'],
['t', 'reuse-mzt-header=FILENAME', "reuse the MZT header."],
['o', 'output-file=FILENAME', 'filename to output'],
['h', 'help', 'display this help'],
['v', 'version', 'show version']
]);
var cli = getopt.parseSystem();
var description = "A simple Z80 assembler -- " + npmInfo.name + "@" + npmInfo.version;
getopt.setHelp(
"Usage: mzasm [OPTION] filename [filename ...]\n" +
description + "\n" +
"\n" +
"[[OPTIONS]]\n" +
"\n" +
"Installation: npm install -g mz700-js\n" +
"Repository: https://github.com/takamin/mz700-js");
if(cli.options.help) {
getopt.showHelp();
process.exit(0);
}
if(cli.options.version) {
console.log(description);
process.exit(0);
}
var args = require("hash-arg").get(["input_filenames:string[]"], cli.argv);
if(cli.argv.length < 1) { |
// Determine the output filename
var output_filename = null;
if('output-file' in cli.options) {
output_filename = cli.options['output-file'];
} else {
var ext = null;
if('reuse-mzt-header' in cli.options
|| 'output-MZT-header' in cli.options)
{
ext = ".mzt";
} else {
ext = ".bin";
}
let input_filename = args.input_filenames[0];
output_filename = changeExt(input_filename, ext);
}
// Determine filename of address map
var fnMap = null;
if('map' in cli.options) {
fnMap = cli.options['map'];
} else {
fnMap = changeExt(output_filename, ".map");
}
//
// MZT-Header
//
var mzt_header = null;
if('reuse-mzt-header' in cli.options) {
//
// Load MZT-Header from other MZT-File.
//
var mzt_filebuf = fs.readFileSync(cli.options['reuse-mzt-header']);
mzt_header = new MZ_TapeHeader(mzt_filebuf, 0);
} else if('output-MZT-header' in cli.options) {
//
// Create MZT-Header from the informations specified in command line options
//
var load_addr = 0;
var exec_addr = 0;
if('loading-address' in cli.options) {
load_addr = parseInt(cli.options['loading-address'], 0);
exec_addr = load_addr;
}
if('execution-address' in cli.options) {
exec_addr = parseInt(cli.options['execution-address'], 0);
}
mzt_header = MZ_TapeHeader.createNew();
mzt_header.setFilename(output_filename);
mzt_header.setAddrLoad(load_addr);
mzt_header.setAddrExec(exec_addr);
}
(async function() {
let sources = [];
await Promise.all(args.input_filenames.map( input_filename => {
return new Promise( (resolve, reject) => {
fs.readFile(input_filename, 'utf-8', function(err, data) {
if(err) {
reject(err);
} else {
sources.push(data);
resolve(data);
}
});
});
}));
//
// Assemble
//
let asm = Z80_assemble.assemble(sources);
//
// Set binary size to MZT Header
//
var mzt_header_buf = [];
if(mzt_header != null) {
if(mzt_header.addrLoad == 0) {
mzt_header.setAddrLoad(asm.minAddr);
}
if(mzt_header.addrExec == 0) {
mzt_header.setAddrExec(asm.minAddr);
}
mzt_header.setFilesize(asm.buffer.length);
mzt_header_buf = mzt_header.buffer;
}
//
// Write out
//
fs.writeFileSync(
output_filename,
Buffer.from(mzt_header_buf.concat(asm.buffer)));
//
// Output address map
//
let map = Z80_assemble.hashMapArray(asm.label2value).map(function(item) {
return [item.label, ":\t", NumberUtil.HEX(item.address, 4), "H"].join('');
}).join("\n");
if(map.length > 0) {
fs.writeFileSync(fnMap, map);
}
}()); | console.error('error: no input file');
process.exit(-1);
} | random_line_split |
setup.py | """
# setup module
"""
import os
from setuptools import setup, find_packages
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, 'README.md')) as f:
README = f.read()
# with open(os.path.join(HERE, 'CHANGES.txt')) as f:
# CHANGES = f.read()
CHANGES = "Changes"
PREQ = [
'pyramid',
'python-keystoneclient',
'python-swiftclient',
'pyyaml',
'responses',
'sniffer',
'waitress',
]
PREQ_DEV = [
'coverage',
'flake8',
'mock',
'nose',
'pylint',
'pyramid',
'tissue', | setup(
name='codebase',
version='0.0.1',
description='Coding demo for Python',
long_description=README + '\n\n' + CHANGES,
classifiers=["Programming Language :: Python",
"Framework :: Pyramid",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application"],
author='Jason Zhu',
author_email='yuxin.zhu@hp.com',
url='',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=PREQ,
tests_require=PREQ_DEV,
test_suite="codebase",
entry_points="""\
[paste.app_factory]
main = codebase:main
""",
) | 'webtest',
'tox',
]
| random_line_split |
common.js | /**
* Common utilities
* @module glMatrix
*/
// Configuration Constants
export var EPSILON = 0.000001;
export var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
export var RANDOM = Math.random;
/**
* Sets the type of array used when creating new vectors and matrices
*
* @param {Type} type Array type, such as Float32Array or Array
*/
export function setMatrixArrayType(type) |
var degree = Math.PI / 180;
/**
* Convert Degree To Radian
*
* @param {Number} a Angle in Degrees
*/
export function toRadian(a) {
return a * degree;
}
/**
* Tests whether or not the arguments have approximately the same value, within an absolute
* or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less
* than or equal to 1.0, and a relative tolerance is used for larger values)
*
* @param {Number} a The first number to test.
* @param {Number} b The second number to test.
* @returns {Boolean} True if the numbers are approximately equal, false otherwise.
*/
export function equals(a, b) {
return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));
}
if (!Math.hypot) Math.hypot = function () {
var y = 0,
i = arguments.length;
while (i--) {
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
}; | {
ARRAY_TYPE = type;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.