file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
numberFormatter.py
import math def formatAmount(val, prec=3, lowest=0, highest=0, currency=False, forceSign=False): """ Add suffix to value, transform value to match new suffix and round it. Keyword arguments: val -- value to process prec -- precision of final number (number of significant positions to show) lowest -- lowest order for suffixizing for numbers 0 < |num| < 1 highest -- highest order for suffixizing for numbers |num| > 1 currency -- if currency, billion suffix will be B instead of G forceSign -- if True, positive numbers are signed too """ if val is None: return "" # Define suffix maps posSuffixMap = {3: "k", 6: "M", 9: "B" if currency is True else "G"} negSuffixMap = {-6: '\u03bc', -3: "m"} # Define tuple of the map keys # As we're going to go from the biggest order of abs(key), sort # them differently due to one set of values being negative # and other positive posOrders = tuple(sorted(iter(posSuffixMap.keys()), reverse=True)) negOrders = tuple(sorted(iter(negSuffixMap.keys()), reverse=False)) # Find the least abs(key) posLowest = min(posOrders) negHighest = max(negOrders) # By default, mantissa takes just value and no suffix mantissa, suffix = val, "" # Positive suffixes if abs(val) > 1 and highest >= posLowest: # Start from highest possible suffix for key in posOrders: # Find first suitable suffix and check if it's not above highest order if abs(val) >= 10 ** key and key <= highest: mantissa, suffix = val / float(10 ** key), posSuffixMap[key] # Do additional step to eliminate results like 999999 => 1000k # If we're already using our greatest order, we can't do anything useful if posOrders.index(key) == 0: break else: # Get order greater than current prevKey = posOrders[posOrders.index(key) - 1] # Check if the key to which we potentially can change is greater # than our highest boundary if prevKey > highest: # If it is, bail - we already have acceptable results break # Find multiplier to get from one order to another orderDiff = 10 ** (prevKey - key) # If rounded mantissa according to our specifications is greater than # or equal to multiplier if roundToPrec(mantissa, prec) >= orderDiff: # Divide mantissa and use suffix of greater order mantissa, suffix = mantissa / orderDiff, posSuffixMap[prevKey] # Otherwise consider current results as acceptable break # Take numbers between 0 and 1, and matching/below highest possible negative suffix elif abs(val) < 1 and val != 0 and lowest <= negHighest: # Start from lowest possible suffix for key in negOrders: # Get next order try: nextKey = negOrders[negOrders.index(key) + 1] except IndexError: nextKey = 0 # Check if mantissa with next suffix is in range [1, 1000) if abs(val) < 10 ** nextKey and key >= lowest: mantissa, suffix = val / float(10 ** key), negSuffixMap[key] # Do additional step to eliminate results like 0.9999 => 1000m # Check if the key we're potentially switching to is greater than our # upper boundary if nextKey > highest: # If it is, leave loop with results we already have break # Find the multiplier between current and next order orderDiff = 10 ** (nextKey - key) # If rounded mantissa according to our specifications is greater than # or equal to multiplier if roundToPrec(mantissa, prec) >= orderDiff: # Divide mantissa and use suffix of greater order # Use special handling of zero key as it's not on the map mantissa, suffix = mantissa / orderDiff, posSuffixMap[nextKey] if nextKey != 0 else "" # Otherwise consider current results as acceptable break # Round mantissa according to our prec variable mantissa = roundToPrec(mantissa, prec) sign = "+" if forceSign is True and mantissa > 0 else "" # Round mantissa and add suffix result = "{0}{1}{2}".format(sign, mantissa, suffix) return result def roundToPrec(val, prec): # We're not rounding integers anyway # Also make sure that we do not ask to calculate logarithm of zero if int(val) == val: return int(val) # Find round factor, taking into consideration that we want to keep at least prec # positions for fractions with zero integer part (e.g. 0.0000354 for prec=3) roundFactor = int(prec - math.ceil(math.log10(abs(val)))) # But we don't want to round integers if roundFactor < 0: roundFactor = 0 # Do actual rounding val = round(val, roundFactor) # Make sure numbers with .0 part designating float don't get through if int(val) == val:
return val def roundDec(val, prec): if int(val) == val: return int(val) return round(val, prec)
val = int(val)
conditional_block
restycheck.js
var openresty = null var Server = 'api.openresty.org'; var savedAnchor = null; var timer = null; $(document).ready(init); var Links = [ ['/=/view/t/a/水煮鱼', {c:'北京',_user:"lifecai.s",t:50}], ['/=/view/Honorlist/limit/500', {_user:'qyliu.Public'}], ['/=/model/Post/~/~', {_offset:0, _count: 10, _user:'agentzh.Public'}], ['/=/view/FetchTitles/~/~', {container:'review', parentid:0, offset:0, count:11, child_offset:0, child_count:5, dsc:'desc', orderby:'updated', _user: 'carrie.Public'}], ['/=/view/FetchResults/~/~', {offset:0, _user:'people.Public', parentid:0, url:'http://www.yahoo.cn/person/bbs/index.html?id=%E5%88%98%E5%BE%B7%E5%8D%8E', offset:0, count:11, child_offset:0, child_count:5, dsc:'desc', orderby: 'support+deny,id'}], ['/=/view/ipbase/~/~', {q:'124.1.34.1', _user:'ipbase.Public'}], ['/=/view/getquery/spell/yao', { _user: 'yquestion.Public' }] ] function init () { if (timer) { clearInterval(timer); } dispatchByAnchor(); timer = setInterval(dispatchByAnchor, 600); } function dispatchByAnchor () { var anchor = location.hash; anchor = anchor.replace(/^\#/, ''); if (savedAnchor == anchor) return; if (anchor == "") { anchor = Server; location.hash = Server; } savedAnchor = anchor; if (anchor) { server = anchor; } else { server = Server; } openresty = new OpenResty.Client( { server: server } ); openresty.callback = function (res) { renderCaptcha(res, 'en'); }; openresty.get('/=/captcha/id', { _lang: 'en' }); openresty.callback = function (res) { renderCaptcha(res, 'cn'); }; openresty.get('/=/captcha/id', { _lang: 'cn' }); $("tr.result").remove(); for (var i = 0; i < Links.length; i++) { //alert("i = " + i); var link = Links[i]; genCallback(link); //for (var j = 0; j < 3; j++) { openresty.get(link[0], link[1]); //} } } function renderCaptcha (res, lang) { if (!openresty.isSuccess(res)) { $("#captcha-" + lang).html("<span class=\"error\">Failed to get captcha ID: " + res.error + "</span>"); return; } var url = 'http://' + server + '/=/captcha/id/' + res; $("#captcha-" + lang).html("<img src=\"" + url + "\">"); } function now () { return (new Date()).getTime(); } function genCallback (link) { var beginTime = now(); openresty.callback = function (res) { var elapsed = now() - beginTime; renderRes([link[0], link[1]], elapsed, res); }; } function renderRes (link, elapsed, res) { //alert("HERE!"); var row; var account = link[1]._user.replace(/\.\w+/, ''); if (!openresty.isSuccess(res)) { //alert("Failed!"); row = [ '<span class="error">Fail</span>', elapsed.toString() + " ms", 'Hash', res.error, account, toURL(link) ]; } else { //alert("Success!"); var type; if (typeof res == 'object') { if (res instanceof Array) { type = 'Array'; } else { type = 'object'; } } else { type = typeof res; } row = [ '<span class="success">Success</span>', elapsed.toString() + " ms", type, res.length, account, toURL(link) ]; } var html = genRowHtml(row); //alert(html); //alert($('#res>tbody').html()); $("#res>tbody").append(html); } function genRowHtml
var html = '<tr class="result">'; for (var i = 0; i < row.length; i++) { html += '<td>' + row[i] + '</td>'; } html += '</tr>\n'; return html; } function toURL (link) { var url = 'http://' + server + link[0] + '?'; var firstTime = true; var params = link[1]; for (var key in params) { if (key == 'callback' || key == '_rand') continue; if (firstTime) { firstTime = false; } else { url += '&'; } url += key + '=' + params[key]; } return url; }
(row) {
identifier_name
restycheck.js
var openresty = null var Server = 'api.openresty.org'; var savedAnchor = null; var timer = null; $(document).ready(init); var Links = [ ['/=/view/t/a/水煮鱼', {c:'北京',_user:"lifecai.s",t:50}], ['/=/view/Honorlist/limit/500', {_user:'qyliu.Public'}], ['/=/model/Post/~/~', {_offset:0, _count: 10, _user:'agentzh.Public'}], ['/=/view/FetchTitles/~/~', {container:'review', parentid:0, offset:0, count:11, child_offset:0, child_count:5, dsc:'desc', orderby:'updated', _user: 'carrie.Public'}], ['/=/view/FetchResults/~/~', {offset:0, _user:'people.Public', parentid:0, url:'http://www.yahoo.cn/person/bbs/index.html?id=%E5%88%98%E5%BE%B7%E5%8D%8E', offset:0, count:11, child_offset:0, child_count:5, dsc:'desc', orderby: 'support+deny,id'}], ['/=/view/ipbase/~/~', {q:'124.1.34.1', _user:'ipbase.Public'}], ['/=/view/getquery/spell/yao', { _user: 'yquestion.Public' }] ] function init () { if (timer) { clearInterval(timer); } dispatchByAnchor(); timer = setInterval(dispatchByAnchor, 600); } function dispatchByAnchor () { var anchor = location.hash; anchor = anchor.replace(/^\#/, ''); if (savedAnchor == anchor) return; if (anchor == "") { anchor = Server; location.hash = Server; } savedAnchor = anchor; if (anchor) { server = anchor; } else { server = Server; } openresty = new OpenResty.Client( { server: server } ); openresty.callback = function (res) { renderCaptcha(res, 'en'); }; openresty.get('/=/captcha/id', { _lang: 'en' }); openresty.callback = function (res) { renderCaptcha(res, 'cn'); }; openresty.get('/=/captcha/id', { _lang: 'cn' }); $("tr.result").remove(); for (var i = 0; i < Links.length; i++) { //alert("i = " + i); var link = Links[i]; genCallback(link); //for (var j = 0; j < 3; j++) { openresty.get(link[0], link[1]); //} } } function renderCaptcha (res, lang) { if (!openresty.isSuccess(res)) { $("#captcha-" + lang).html("<span class=\"error\">Failed to get captcha ID: " + res.error + "</span>"); return; } var url = 'http://' + server + '/=/captcha/id/' + res; $("#captcha-" + lang).html("<img src=\"" + url + "\">");
function genCallback (link) { var beginTime = now(); openresty.callback = function (res) { var elapsed = now() - beginTime; renderRes([link[0], link[1]], elapsed, res); }; } function renderRes (link, elapsed, res) { //alert("HERE!"); var row; var account = link[1]._user.replace(/\.\w+/, ''); if (!openresty.isSuccess(res)) { //alert("Failed!"); row = [ '<span class="error">Fail</span>', elapsed.toString() + " ms", 'Hash', res.error, account, toURL(link) ]; } else { //alert("Success!"); var type; if (typeof res == 'object') { if (res instanceof Array) { type = 'Array'; } else { type = 'object'; } } else { type = typeof res; } row = [ '<span class="success">Success</span>', elapsed.toString() + " ms", type, res.length, account, toURL(link) ]; } var html = genRowHtml(row); //alert(html); //alert($('#res>tbody').html()); $("#res>tbody").append(html); } function genRowHtml (row) { var html = '<tr class="result">'; for (var i = 0; i < row.length; i++) { html += '<td>' + row[i] + '</td>'; } html += '</tr>\n'; return html; } function toURL (link) { var url = 'http://' + server + link[0] + '?'; var firstTime = true; var params = link[1]; for (var key in params) { if (key == 'callback' || key == '_rand') continue; if (firstTime) { firstTime = false; } else { url += '&'; } url += key + '=' + params[key]; } return url; }
} function now () { return (new Date()).getTime(); }
random_line_split
restycheck.js
var openresty = null var Server = 'api.openresty.org'; var savedAnchor = null; var timer = null; $(document).ready(init); var Links = [ ['/=/view/t/a/水煮鱼', {c:'北京',_user:"lifecai.s",t:50}], ['/=/view/Honorlist/limit/500', {_user:'qyliu.Public'}], ['/=/model/Post/~/~', {_offset:0, _count: 10, _user:'agentzh.Public'}], ['/=/view/FetchTitles/~/~', {container:'review', parentid:0, offset:0, count:11, child_offset:0, child_count:5, dsc:'desc', orderby:'updated', _user: 'carrie.Public'}], ['/=/view/FetchResults/~/~', {offset:0, _user:'people.Public', parentid:0, url:'http://www.yahoo.cn/person/bbs/index.html?id=%E5%88%98%E5%BE%B7%E5%8D%8E', offset:0, count:11, child_offset:0, child_count:5, dsc:'desc', orderby: 'support+deny,id'}], ['/=/view/ipbase/~/~', {q:'124.1.34.1', _user:'ipbase.Public'}], ['/=/view/getquery/spell/yao', { _user: 'yquestion.Public' }] ] function init () { if (timer) { clearInterval(timer); } dispatchByAnchor(); timer = setInterval(dispatchByAnchor, 600); } function dispatchByAnchor () { var anchor = location.hash; anchor = anchor.replace(/^\#/, ''); if (savedAnchor == anchor) return; if (anchor == "") { anchor = Server; location.hash = Server; } savedAnchor = anchor; if (anchor) { server = anchor; } else { server = Server; } openresty = new OpenResty.Client( { server: server } ); openresty.callback = function (res) { renderCaptcha(res, 'en'); }; openresty.get('/=/captcha/id', { _lang: 'en' }); openresty.callback = function (res) { renderCaptcha(res, 'cn'); }; openresty.get('/=/captcha/id', { _lang: 'cn' }); $("tr.result").remove(); for (var i = 0; i < Links.length; i++) { //alert("i = " + i); var link = Links[i]; genCallback(link); //for (var j = 0; j < 3; j++) { openresty.get(link[0], link[1]); //} } } function renderCaptcha (res, lang) { if (!openresty.isSuccess(res)) { $("#captcha-" + lang).html("<span class=\"error\">Failed to get captcha ID: " + res.error + "</span>"); return; } var url = 'http://' + server + '/=/captcha/id/' + res; $("#captcha-" + lang).html("<img src=\"" + url + "\">"); } function now () { return (new Date()).getTime(); } function genCallback (link) { var beginTime = now(); openresty.callback = function (res) { var elapsed = now() - beginTime; renderRes([link[0], link[1]], elapsed, res); }; } function renderRes (link, elapsed, res) { //alert("HERE!"); var row; var account = link[1]._user.replace(/\.\w+/, ''); if (!openresty.isSuccess(res)) { //alert("Failed!"); row = [ '<span class="error">Fail</span>', elapsed.toString() + " ms", 'Hash', res.error, account, toURL(link) ]; } else { //alert("Success!"); var type; if (typeof res == 'object') { if (res instanceof Array) { type = 'Array'; } else { type = 'object'; } } else { type = typeof res; } row = [ '<span class="success">Success</span>', elapsed.toString() + " ms", type, res.length, account, toURL(link) ]; } var html = genRowHtml(row); //alert(html); //alert($('#res>tbody').html()); $("#res>tbody").append(html); } function genRowHtml (row) { var
toURL (link) { var url = 'http://' + server + link[0] + '?'; var firstTime = true; var params = link[1]; for (var key in params) { if (key == 'callback' || key == '_rand') continue; if (firstTime) { firstTime = false; } else { url += '&'; } url += key + '=' + params[key]; } return url; }
html = '<tr class="result">'; for (var i = 0; i < row.length; i++) { html += '<td>' + row[i] + '</td>'; } html += '</tr>\n'; return html; } function
identifier_body
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ "jsonschema" # TODO: put package requirements here ] test_requirements = [ "jsonschema" # TODO: put package test requirements here
setup( name='pycorm', version='0.2.13', description="a pico orm that uses jsonschema", long_description=readme + '\n\n' + history, author="Johannes Valbjørn", author_email='johannes.valbjorn@gmail.com', url='https://github.com/sloev/pycorm', packages=[ 'pycorm', ], package_dir={'pycorm': 'pycorm'}, include_package_data=True, install_requires=requirements, license="MIT", zip_safe=False, keywords='pycorm', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: ISC License (ISCL)', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7' ], test_suite='tests', tests_require=test_requirements )
]
random_line_split
meetings.js
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function
() { return ( <Layout pageTitle="Meetings" description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event." > <Div maxWidth="1200px" flexd flexWrap="wrap" mt={12} mx="auto" mb={24} jc="space-around" ai="center" > <Span p={[4]} width={[1, 1, 1 / 2]} maxWidth="400px"> <Img /> </Span> <Div p={[8, 8, 4]} pb={[4, 0]} width={[1, 1, 1 / 2]} ff="sans.0"> <Header type={1} fs={["2xl", "3xl"]} color="grey8"> Next Meetup Event </Header> <P fs="lg" color="grey8" lh="normal"> Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event. </P> <Span> <Button as="a" href="https://www.meetup.com/TulsaJS/" target="_blank" rel="nofollow" type="primary" small > Meetup Page </Button> </Span> </Div> </Div> </Layout> ) }
Meetings
identifier_name
meetings.js
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function Meetings() { return ( <Layout pageTitle="Meetings" description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event." > <Div maxWidth="1200px" flexd flexWrap="wrap" mt={12} mx="auto" mb={24} jc="space-around" ai="center" > <Span p={[4]} width={[1, 1, 1 / 2]} maxWidth="400px"> <Img /> </Span> <Div p={[8, 8, 4]} pb={[4, 0]} width={[1, 1, 1 / 2]} ff="sans.0"> <Header type={1} fs={["2xl", "3xl"]} color="grey8"> Next Meetup Event </Header> <P fs="lg" color="grey8" lh="normal"> Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event. </P> <Span> <Button as="a" href="https://www.meetup.com/TulsaJS/" target="_blank" rel="nofollow" type="primary" small > Meetup Page </Button> </Span> </Div> </Div> </Layout> )
}
random_line_split
meetings.js
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function Meetings()
{ return ( <Layout pageTitle="Meetings" description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event." > <Div maxWidth="1200px" flexd flexWrap="wrap" mt={12} mx="auto" mb={24} jc="space-around" ai="center" > <Span p={[4]} width={[1, 1, 1 / 2]} maxWidth="400px"> <Img /> </Span> <Div p={[8, 8, 4]} pb={[4, 0]} width={[1, 1, 1 / 2]} ff="sans.0"> <Header type={1} fs={["2xl", "3xl"]} color="grey8"> Next Meetup Event </Header> <P fs="lg" color="grey8" lh="normal"> Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event. </P> <Span> <Button as="a" href="https://www.meetup.com/TulsaJS/" target="_blank" rel="nofollow" type="primary" small > Meetup Page </Button> </Span> </Div> </Div> </Layout> ) }
identifier_body
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>. //! Ethereum virtual machine. pub mod ext; pub mod evm; pub mod interpreter; #[macro_use] pub mod factory; pub mod schedule; mod vmtype; mod instructions; #[cfg(feature = "jit" )] mod jit; #[cfg(test)] mod tests; #[cfg(all(feature="benches", test))] mod benches; pub use self::evm::{Evm, Error, Finalize, FinalizationResult, GasLeft, Result, CostType, ReturnData}; pub use self::ext::{Ext, ContractCreateResult, MessageCallResult, CreateContractAddress}; pub use self::instructions::{InstructionInfo, INSTRUCTIONS, push_bytes}; pub use self::vmtype::VMType;
pub use self::schedule::{Schedule, CleanDustMode}; pub use types::executed::CallType;
pub use self::factory::Factory;
random_line_split
parity_signing.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
use jsonrpc_core::Error; use futures::BoxFuture; use v1::types::{U256, H160, Bytes, ConfirmationResponse, TransactionRequest, Either}; build_rpc_trait! { /// Signing methods implementation. pub trait ParitySigning { type Metadata; /// Posts sign request asynchronously. /// Will return a confirmation ID for later use with check_transaction. #[rpc(meta, name = "parity_postSign")] fn post_sign(&self, Self::Metadata, H160, Bytes) -> BoxFuture<Either<U256, ConfirmationResponse>, Error>; /// Posts transaction asynchronously. /// Will return a transaction ID for later use with check_transaction. #[rpc(meta, name = "parity_postTransaction")] fn post_transaction(&self, Self::Metadata, TransactionRequest) -> BoxFuture<Either<U256, ConfirmationResponse>, Error>; /// Checks the progress of a previously posted request (transaction/sign). /// Should be given a valid send_transaction ID. #[rpc(name = "parity_checkRequest")] fn check_request(&self, U256) -> Result<Option<ConfirmationResponse>, Error>; /// Decrypt some ECIES-encrypted message. /// First parameter is the address with which it is encrypted, second is the ciphertext. #[rpc(meta, name = "parity_decryptMessage")] fn decrypt_message(&self, Self::Metadata, H160, Bytes) -> BoxFuture<Bytes, Error>; } }
//! ParitySigning rpc interface.
random_line_split
u_char.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault; /// Returns the amount of bytes this character would need if encoded in /// UTF-8. #[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn is_alphabetic(self) -> bool { match self { 'a' ... 'z' | 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool
#[stable] fn is_lowercase(self) -> bool { match self { 'a' ... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { ' ' | '\x09' ... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0' ... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }
{ derived_property::XID_Continue(self) }
identifier_body
u_char.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault; /// Returns the amount of bytes this character would need if encoded in /// UTF-8. #[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn
(self) -> bool { match self { 'a' ... 'z' | 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } #[stable] fn is_lowercase(self) -> bool { match self { 'a' ... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { ' ' | '\x09' ... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0' ... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }
is_alphabetic
identifier_name
u_char.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Unicode-intensive `char` methods along with the `core` methods. //! //! These methods implement functionality for `char` that requires knowledge of //! Unicode definitions, including normalization, categorization, and display information. use core::char; use core::char::CharExt as C; use core::option::Option; use tables::{derived_property, property, general_category, conversions, charwidth}; /// Functionality for manipulating `char`. #[stable] pub trait CharExt { /// Checks if a `char` parses as a numeric digit in the given radix. /// /// Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' and '9', the corresponding value between 0 and /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iterator that yields the hexadecimal Unicode escape /// of a character, as `char`s. /// /// All characters are escaped with Rust syntax of the form `\\u{NNNN}` /// where `NNNN` is the shortest hexadecimal representation of the code /// point. #[stable] fn escape_unicode(self) -> char::EscapeUnicode; /// Returns an iterator that yields the 'default' ASCII and /// C++11-like literal escape of a character, as `char`s. /// /// The default is chosen with a bias toward producing literals that are /// legal in a variety of languages, including C++11 and similar C-family /// languages. The exact rules are: /// /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. /// * Single-quote, double-quote and backslash chars are backslash- /// escaped. /// * Any other chars in the range [0x20,0x7e] are not escaped. /// * Any other chars are given hex Unicode escapes; see `escape_unicode`. #[stable] fn escape_default(self) -> char::EscapeDefault;
#[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>; /// Encodes this character as UTF-16 into the provided `u16` buffer, /// and then returns the number of `u16`s written. /// /// If the buffer is not large enough, nothing will be written into it /// and a `None` will be returned. #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>; /// Returns whether the specified character is considered a Unicode /// alphabetic code point. #[stable] fn is_alphabetic(self) -> bool; /// Returns whether the specified character satisfies the 'XID_Start' /// Unicode property. /// /// 'XID_Start' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to ID_Start but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool; /// Returns whether the specified `char` satisfies the 'XID_Continue' /// Unicode property. /// /// 'XID_Continue' is a Unicode Derived Property specified in /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), /// mostly similar to 'ID_Continue' but modified for closure under NFKx. #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool; /// Indicates whether a character is in lowercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Lowercase`. #[stable] fn is_lowercase(self) -> bool; /// Indicates whether a character is in uppercase. /// /// This is defined according to the terms of the Unicode Derived Core /// Property `Uppercase`. #[stable] fn is_uppercase(self) -> bool; /// Indicates whether a character is whitespace. /// /// Whitespace is defined in terms of the Unicode Property `White_Space`. #[stable] fn is_whitespace(self) -> bool; /// Indicates whether a character is alphanumeric. /// /// Alphanumericness is defined in terms of the Unicode General Categories /// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'. #[stable] fn is_alphanumeric(self) -> bool; /// Indicates whether a character is a control code point. /// /// Control code points are defined in terms of the Unicode General /// Category `Cc`. #[stable] fn is_control(self) -> bool; /// Indicates whether the character is numeric (Nd, Nl, or No). #[stable] fn is_numeric(self) -> bool; /// Converts a character to its lowercase equivalent. /// /// The case-folding performed is the common or simple mapping. See /// `to_uppercase()` for references and more information. /// /// # Return value /// /// Returns the lowercase equivalent of the character, or the character /// itself if no conversion is possible. #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char; /// Converts a character to its uppercase equivalent. /// /// The case-folding performed is the common or simple mapping: it maps /// one Unicode codepoint (one character in Rust) to its uppercase /// equivalent according to the Unicode database [1]. The additional /// [`SpecialCasing.txt`] is not considered here, as it expands to multiple /// codepoints in some cases. /// /// A full reference can be found here [2]. /// /// # Return value /// /// Returns the uppercase equivalent of the character, or the character /// itself if no conversion was made. /// /// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt /// /// [`SpecialCasing`.txt`]: ftp://ftp.unicode.org/Public/UNIDATA/SpecialCasing.txt /// /// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992 #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char; /// Returns this character's displayed width in columns, or `None` if it is a /// control character other than `'\x00'`. /// /// `is_cjk` determines behavior for characters in the Ambiguous category: /// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1. /// In CJK contexts, `is_cjk` should be `true`, else it should be `false`. /// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/) /// recommends that these characters be treated as 1 column (i.e., /// `is_cjk` = `false`) if the context cannot be reliably determined. #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint>; } #[stable] impl CharExt for char { #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool { C::is_digit(self, radix) } #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint> { C::to_digit(self, radix) } #[stable] fn escape_unicode(self) -> char::EscapeUnicode { C::escape_unicode(self) } #[stable] fn escape_default(self) -> char::EscapeDefault { C::escape_default(self) } #[stable] fn len_utf8(self) -> uint { C::len_utf8(self) } #[stable] fn len_utf16(self) -> uint { C::len_utf16(self) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> { C::encode_utf8(self, dst) } #[unstable = "pending decision about Iterator/Writer/Reader"] fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> { C::encode_utf16(self, dst) } #[stable] fn is_alphabetic(self) -> bool { match self { 'a' ... 'z' | 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false } } #[unstable = "mainly needed for compiler internals"] fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } #[unstable = "mainly needed for compiler internals"] fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } #[stable] fn is_lowercase(self) -> bool { match self { 'a' ... 'z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false } } #[stable] fn is_uppercase(self) -> bool { match self { 'A' ... 'Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false } } #[stable] fn is_whitespace(self) -> bool { match self { ' ' | '\x09' ... '\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false } } #[stable] fn is_alphanumeric(self) -> bool { self.is_alphabetic() || self.is_numeric() } #[stable] fn is_control(self) -> bool { general_category::Cc(self) } #[stable] fn is_numeric(self) -> bool { match self { '0' ... '9' => true, c if c > '\x7f' => general_category::N(c), _ => false } } #[unstable = "pending case transformation decisions"] fn to_lowercase(self) -> char { conversions::to_lower(self) } #[unstable = "pending case transformation decisions"] fn to_uppercase(self) -> char { conversions::to_upper(self) } #[unstable = "needs expert opinion. is_cjk flag stands out as ugly"] fn width(self, is_cjk: bool) -> Option<uint> { charwidth::width(self, is_cjk) } }
/// Returns the amount of bytes this character would need if encoded in /// UTF-8.
random_line_split
lib.rs
#![feature(globs)] use std::collections::HashMap; use std::fmt::{Show, FormatError, Formatter}; use std::os; use std::str; pub use self::gnu::GnuMakefile; // XXX: no idea why this is necessary #[path = "gnu/mod.rs"] pub mod gnu; pub type TokenResult<T> = Result<T, TokenError>; pub type ParseResult<T> = Result<T, ParseError>; pub trait Makefile<'a> { fn vars(&mut self) -> &mut MutableMap<&'a [u8], Vec<u8>>; fn tokenize<'a>(&mut self, data: &[u8]) -> TokenResult<Vec<Token<'a>>>; fn parse<'a, 'b>(&mut self, tokens: Vec<Token<'b>>) -> ParseResult<MakefileDag<'a>>; fn find_var<'b>(&'b mut self, name: &'a [u8]) -> Option<Vec<u8>> { let vars = self.vars(); match vars.find(&name).and_then(|val| Some(val.clone())) { // get the borrow checker to shut up None => { if let Some(utf8_name) = str::from_utf8(name) { match os::getenv_as_bytes(utf8_name) { Some(val) => { vars.insert(name, val.clone()); Some(val) } None => None } } else { None } } val => val } } } pub enum Token<'a> { Ident(&'a [u8]), Var(&'a [u8]), // NOTE: both Var and FuncCall have the same syntax FuncCall(&'a [u8]), Command(&'a Token<'a>), // i.e. shell commands in a rule (Token should be Other) Colon, Equal, Comma, Dollar, Question, Plus, Tab, IfEq, IfNeq, Other(&'a [u8]) } pub struct
<'a> { rules: HashMap<&'a [u8], MakefileRule<'a>>, funcs: HashMap<&'a [u8], &'a [u8]> } pub struct MakefileRule<'a> { name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8] } pub struct ParseError { pub message: String, pub code: int } pub struct TokenError { pub message: String, pub code: int } impl<'a> MakefileDag<'a> { #[inline] pub fn new() -> MakefileDag<'a> { MakefileDag { rules: HashMap::new(), funcs: HashMap::new(), } } } impl<'a> MakefileRule<'a> { #[inline] pub fn new(name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8]) -> MakefileRule<'a> { MakefileRule { name: name, deps: deps, body: body } } } impl ParseError { #[inline] pub fn new(msg: String, code: int) -> ParseError { ParseError { message: msg, code: code } } } impl Show for ParseError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } } impl TokenError { #[inline] pub fn new(msg: String, code: int) -> TokenError { TokenError { message: msg, code: code } } } impl Show for TokenError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } }
MakefileDag
identifier_name
lib.rs
#![feature(globs)] use std::collections::HashMap; use std::fmt::{Show, FormatError, Formatter}; use std::os; use std::str; pub use self::gnu::GnuMakefile; // XXX: no idea why this is necessary #[path = "gnu/mod.rs"] pub mod gnu; pub type TokenResult<T> = Result<T, TokenError>; pub type ParseResult<T> = Result<T, ParseError>; pub trait Makefile<'a> { fn vars(&mut self) -> &mut MutableMap<&'a [u8], Vec<u8>>; fn tokenize<'a>(&mut self, data: &[u8]) -> TokenResult<Vec<Token<'a>>>; fn parse<'a, 'b>(&mut self, tokens: Vec<Token<'b>>) -> ParseResult<MakefileDag<'a>>; fn find_var<'b>(&'b mut self, name: &'a [u8]) -> Option<Vec<u8>> { let vars = self.vars(); match vars.find(&name).and_then(|val| Some(val.clone())) { // get the borrow checker to shut up None => { if let Some(utf8_name) = str::from_utf8(name) { match os::getenv_as_bytes(utf8_name) { Some(val) => { vars.insert(name, val.clone()); Some(val) } None => None } } else { None } } val => val } } } pub enum Token<'a> { Ident(&'a [u8]), Var(&'a [u8]), // NOTE: both Var and FuncCall have the same syntax FuncCall(&'a [u8]), Command(&'a Token<'a>), // i.e. shell commands in a rule (Token should be Other) Colon, Equal, Comma, Dollar, Question, Plus, Tab, IfEq, IfNeq, Other(&'a [u8]) } pub struct MakefileDag<'a> { rules: HashMap<&'a [u8], MakefileRule<'a>>, funcs: HashMap<&'a [u8], &'a [u8]> } pub struct MakefileRule<'a> { name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8] } pub struct ParseError { pub message: String, pub code: int } pub struct TokenError { pub message: String, pub code: int } impl<'a> MakefileDag<'a> { #[inline] pub fn new() -> MakefileDag<'a> { MakefileDag { rules: HashMap::new(), funcs: HashMap::new(), }
} impl<'a> MakefileRule<'a> { #[inline] pub fn new(name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8]) -> MakefileRule<'a> { MakefileRule { name: name, deps: deps, body: body } } } impl ParseError { #[inline] pub fn new(msg: String, code: int) -> ParseError { ParseError { message: msg, code: code } } } impl Show for ParseError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } } impl TokenError { #[inline] pub fn new(msg: String, code: int) -> TokenError { TokenError { message: msg, code: code } } } impl Show for TokenError { fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> { formatter.write(self.message.as_bytes()) } }
}
random_line_split
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) {
} } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn description(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
unsafe { ttf::TTF_Quit();
random_line_split
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) { unsafe { ttf::TTF_Quit(); } } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf, 'static>, String>
/// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn description(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
{ internal_load_font(path, point_size) }
identifier_body
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) { unsafe { ttf::TTF_Quit(); } } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null()
else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn description(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
{ Err(get_error()) }
conditional_block
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to manage C code initialization and clean-up. #[must_use] pub struct Sdl2TtfContext; // Clean up the context once it goes out of scope impl Drop for Sdl2TtfContext { fn drop(&mut self) { unsafe { ttf::TTF_Quit(); } } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font(path, point_size) } /// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font_at_index(path, index, point_size) } /// Loads a font from the given SDL2 rwops object with the given size in /// points. pub fn load_font_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontRW(rwops.raw(), 0, point_size as c_int) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } /// Loads the font at the given index of the SDL2 rwops object with /// the given size in points. pub fn load_font_at_index_from_rwops<'ttf, 'r>( &'ttf self, rwops: RWops<'r>, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'r>, String> { let raw = unsafe { ttf::TTF_OpenFontIndexRW(rwops.raw(), 0, point_size as c_int, index as c_long) }; if (raw as *mut ()).is_null() { Err(get_error()) } else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized twice /// Necessary for context management, unless we find a way to have a singleton #[derive(Debug)] pub enum InitError { InitializationError(io::Error), AlreadyInitializedError, } impl error::Error for InitError { fn
(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError::AlreadyInitializedError => None, InitError::InitializationError(ref error) => Some(error), } } } impl fmt::Display for InitError { fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { formatter.write_str("SDL2_TTF has already been initialized") } } /// Initializes the truetype font API and returns a context manager which will /// clean up the library once it goes out of scope. pub fn init() -> Result<Sdl2TtfContext, InitError> { unsafe { if ttf::TTF_WasInit() == 1 { Err(InitError::AlreadyInitializedError) } else if ttf::TTF_Init() == 0 { Ok(Sdl2TtfContext) } else { Err(InitError::InitializationError(io::Error::last_os_error())) } } } /// Returns whether library has been initialized already. pub fn has_been_initialized() -> bool { unsafe { ttf::TTF_WasInit() == 1 } }
description
identifier_name
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 'threading'. # # Try calling `multiprocessing.doc.main()` to read the html # documentation in a webbrowser. # # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: #
# 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # __version__ = '0.70a1' __all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger', 'allow_connection_pickling', 'BufferTooShort', 'TimeoutError', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array', 'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING', ] __author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)' # # Imports # import os import sys from multiprocessing.process import Process, current_process, active_children from multiprocessing.util import SUBDEBUG, SUBWARNING # # Exceptions # class ProcessError(Exception): pass class BufferTooShort(ProcessError): pass class TimeoutError(ProcessError): pass class AuthenticationError(ProcessError): pass # This is down here because _multiprocessing uses BufferTooShort #import _multiprocessing # # Definitions not depending on native semaphores # def Manager(): ''' Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. ''' from multiprocessing.managers import SyncManager m = SyncManager() m.start() return m def Pipe(duplex=True, buffer_id = None): ''' Returns two connection object connected by a pipe ''' from multiprocessing.connection import Pipe return Pipe(duplex, buffer_id) def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def freeze_support(): ''' Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. ''' if sys.platform == 'win32' and getattr(sys, 'frozen', False): from multiprocessing.forking import freeze_support freeze_support() def get_logger(): ''' Return package logger -- if it does not already exist then it is created ''' from multiprocessing.util import get_logger return get_logger() def log_to_stderr(level=None): ''' Turn on logging and add a handler which prints to stderr ''' from multiprocessing.util import log_to_stderr return log_to_stderr(level) def allow_connection_pickling(): ''' Install support for sending connections and sockets between processes ''' from multiprocessing import reduction # # Definitions depending on native semaphores # def Lock(): ''' Returns a non-recursive lock object ''' from multiprocessing.synchronize import Lock return Lock() def RLock(): ''' Returns a recursive lock object ''' from multiprocessing.synchronize import RLock return RLock() def Condition(lock=None): ''' Returns a condition object ''' from multiprocessing.synchronize import Condition return Condition(lock) def Semaphore(value=1): ''' Returns a semaphore object ''' from multiprocessing.synchronize import Semaphore return Semaphore(value) def BoundedSemaphore(value=1): ''' Returns a bounded semaphore object ''' from multiprocessing.synchronize import BoundedSemaphore return BoundedSemaphore(value) def Event(): ''' Returns an event object ''' from multiprocessing.synchronize import Event return Event() def Queue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import Queue return Queue(maxsize) def JoinableQueue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import JoinableQueue return JoinableQueue(maxsize) def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None): ''' Returns a process pool object ''' from multiprocessing.pool import Pool return Pool(processes, initializer, initargs, maxtasksperchild) def RawValue(typecode_or_type, *args): ''' Returns a shared object ''' from multiprocessing.sharedctypes import RawValue return RawValue(typecode_or_type, *args) def RawArray(typecode_or_type, size_or_initializer): ''' Returns a shared array ''' from multiprocessing.sharedctypes import RawArray return RawArray(typecode_or_type, size_or_initializer) def Value(typecode_or_type, *args, **kwds): ''' Returns a synchronized shared object ''' from multiprocessing.sharedctypes import Value return Value(typecode_or_type, *args, **kwds) def Array(typecode_or_type, size_or_initializer, **kwds): ''' Returns a synchronized shared array ''' from multiprocessing.sharedctypes import Array return Array(typecode_or_type, size_or_initializer, **kwds) # # # if sys.platform == 'win32': def set_executable(executable): ''' Sets the path to a python.exe or pythonw.exe binary used to run child processes on Windows instead of sys.executable. Useful for people embedding Python. ''' from multiprocessing.forking import set_executable set_executable(executable) __all__ += ['set_executable']
random_line_split
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 'threading'. # # Try calling `multiprocessing.doc.main()` to read the html # documentation in a webbrowser. # # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # __version__ = '0.70a1' __all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger', 'allow_connection_pickling', 'BufferTooShort', 'TimeoutError', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array', 'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING', ] __author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)' # # Imports # import os import sys from multiprocessing.process import Process, current_process, active_children from multiprocessing.util import SUBDEBUG, SUBWARNING # # Exceptions # class ProcessError(Exception): pass class
(ProcessError): pass class TimeoutError(ProcessError): pass class AuthenticationError(ProcessError): pass # This is down here because _multiprocessing uses BufferTooShort #import _multiprocessing # # Definitions not depending on native semaphores # def Manager(): ''' Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. ''' from multiprocessing.managers import SyncManager m = SyncManager() m.start() return m def Pipe(duplex=True, buffer_id = None): ''' Returns two connection object connected by a pipe ''' from multiprocessing.connection import Pipe return Pipe(duplex, buffer_id) def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def freeze_support(): ''' Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. ''' if sys.platform == 'win32' and getattr(sys, 'frozen', False): from multiprocessing.forking import freeze_support freeze_support() def get_logger(): ''' Return package logger -- if it does not already exist then it is created ''' from multiprocessing.util import get_logger return get_logger() def log_to_stderr(level=None): ''' Turn on logging and add a handler which prints to stderr ''' from multiprocessing.util import log_to_stderr return log_to_stderr(level) def allow_connection_pickling(): ''' Install support for sending connections and sockets between processes ''' from multiprocessing import reduction # # Definitions depending on native semaphores # def Lock(): ''' Returns a non-recursive lock object ''' from multiprocessing.synchronize import Lock return Lock() def RLock(): ''' Returns a recursive lock object ''' from multiprocessing.synchronize import RLock return RLock() def Condition(lock=None): ''' Returns a condition object ''' from multiprocessing.synchronize import Condition return Condition(lock) def Semaphore(value=1): ''' Returns a semaphore object ''' from multiprocessing.synchronize import Semaphore return Semaphore(value) def BoundedSemaphore(value=1): ''' Returns a bounded semaphore object ''' from multiprocessing.synchronize import BoundedSemaphore return BoundedSemaphore(value) def Event(): ''' Returns an event object ''' from multiprocessing.synchronize import Event return Event() def Queue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import Queue return Queue(maxsize) def JoinableQueue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import JoinableQueue return JoinableQueue(maxsize) def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None): ''' Returns a process pool object ''' from multiprocessing.pool import Pool return Pool(processes, initializer, initargs, maxtasksperchild) def RawValue(typecode_or_type, *args): ''' Returns a shared object ''' from multiprocessing.sharedctypes import RawValue return RawValue(typecode_or_type, *args) def RawArray(typecode_or_type, size_or_initializer): ''' Returns a shared array ''' from multiprocessing.sharedctypes import RawArray return RawArray(typecode_or_type, size_or_initializer) def Value(typecode_or_type, *args, **kwds): ''' Returns a synchronized shared object ''' from multiprocessing.sharedctypes import Value return Value(typecode_or_type, *args, **kwds) def Array(typecode_or_type, size_or_initializer, **kwds): ''' Returns a synchronized shared array ''' from multiprocessing.sharedctypes import Array return Array(typecode_or_type, size_or_initializer, **kwds) # # # if sys.platform == 'win32': def set_executable(executable): ''' Sets the path to a python.exe or pythonw.exe binary used to run child processes on Windows instead of sys.executable. Useful for people embedding Python. ''' from multiprocessing.forking import set_executable set_executable(executable) __all__ += ['set_executable']
BufferTooShort
identifier_name
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 'threading'. # # Try calling `multiprocessing.doc.main()` to read the html # documentation in a webbrowser. # # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # __version__ = '0.70a1' __all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger', 'allow_connection_pickling', 'BufferTooShort', 'TimeoutError', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array', 'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING', ] __author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)' # # Imports # import os import sys from multiprocessing.process import Process, current_process, active_children from multiprocessing.util import SUBDEBUG, SUBWARNING # # Exceptions # class ProcessError(Exception): pass class BufferTooShort(ProcessError): pass class TimeoutError(ProcessError): pass class AuthenticationError(ProcessError): pass # This is down here because _multiprocessing uses BufferTooShort #import _multiprocessing # # Definitions not depending on native semaphores # def Manager(): ''' Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. ''' from multiprocessing.managers import SyncManager m = SyncManager() m.start() return m def Pipe(duplex=True, buffer_id = None): ''' Returns two connection object connected by a pipe ''' from multiprocessing.connection import Pipe return Pipe(duplex, buffer_id) def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin': comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0 else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def freeze_support(): ''' Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. ''' if sys.platform == 'win32' and getattr(sys, 'frozen', False): from multiprocessing.forking import freeze_support freeze_support() def get_logger(): ''' Return package logger -- if it does not already exist then it is created ''' from multiprocessing.util import get_logger return get_logger() def log_to_stderr(level=None): ''' Turn on logging and add a handler which prints to stderr ''' from multiprocessing.util import log_to_stderr return log_to_stderr(level) def allow_connection_pickling(): ''' Install support for sending connections and sockets between processes ''' from multiprocessing import reduction # # Definitions depending on native semaphores # def Lock(): ''' Returns a non-recursive lock object ''' from multiprocessing.synchronize import Lock return Lock() def RLock(): ''' Returns a recursive lock object ''' from multiprocessing.synchronize import RLock return RLock() def Condition(lock=None): ''' Returns a condition object ''' from multiprocessing.synchronize import Condition return Condition(lock) def Semaphore(value=1): ''' Returns a semaphore object ''' from multiprocessing.synchronize import Semaphore return Semaphore(value) def BoundedSemaphore(value=1):
def Event(): ''' Returns an event object ''' from multiprocessing.synchronize import Event return Event() def Queue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import Queue return Queue(maxsize) def JoinableQueue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import JoinableQueue return JoinableQueue(maxsize) def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None): ''' Returns a process pool object ''' from multiprocessing.pool import Pool return Pool(processes, initializer, initargs, maxtasksperchild) def RawValue(typecode_or_type, *args): ''' Returns a shared object ''' from multiprocessing.sharedctypes import RawValue return RawValue(typecode_or_type, *args) def RawArray(typecode_or_type, size_or_initializer): ''' Returns a shared array ''' from multiprocessing.sharedctypes import RawArray return RawArray(typecode_or_type, size_or_initializer) def Value(typecode_or_type, *args, **kwds): ''' Returns a synchronized shared object ''' from multiprocessing.sharedctypes import Value return Value(typecode_or_type, *args, **kwds) def Array(typecode_or_type, size_or_initializer, **kwds): ''' Returns a synchronized shared array ''' from multiprocessing.sharedctypes import Array return Array(typecode_or_type, size_or_initializer, **kwds) # # # if sys.platform == 'win32': def set_executable(executable): ''' Sets the path to a python.exe or pythonw.exe binary used to run child processes on Windows instead of sys.executable. Useful for people embedding Python. ''' from multiprocessing.forking import set_executable set_executable(executable) __all__ += ['set_executable']
''' Returns a bounded semaphore object ''' from multiprocessing.synchronize import BoundedSemaphore return BoundedSemaphore(value)
identifier_body
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 'threading'. # # Try calling `multiprocessing.doc.main()` to read the html # documentation in a webbrowser. # # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # __version__ = '0.70a1' __all__ = [ 'Process', 'current_process', 'active_children', 'freeze_support', 'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger', 'allow_connection_pickling', 'BufferTooShort', 'TimeoutError', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array', 'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING', ] __author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)' # # Imports # import os import sys from multiprocessing.process import Process, current_process, active_children from multiprocessing.util import SUBDEBUG, SUBWARNING # # Exceptions # class ProcessError(Exception): pass class BufferTooShort(ProcessError): pass class TimeoutError(ProcessError): pass class AuthenticationError(ProcessError): pass # This is down here because _multiprocessing uses BufferTooShort #import _multiprocessing # # Definitions not depending on native semaphores # def Manager(): ''' Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. ''' from multiprocessing.managers import SyncManager m = SyncManager() m.start() return m def Pipe(duplex=True, buffer_id = None): ''' Returns two connection object connected by a pipe ''' from multiprocessing.connection import Pipe return Pipe(duplex, buffer_id) def cpu_count(): ''' Returns the number of CPUs in the system ''' if sys.platform == 'win32': try: num = int(os.environ['NUMBER_OF_PROCESSORS']) except (ValueError, KeyError): num = 0 elif 'bsd' in sys.platform or sys.platform == 'darwin':
else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def freeze_support(): ''' Check whether this is a fake forked process in a frozen executable. If so then run code specified by commandline and exit. ''' if sys.platform == 'win32' and getattr(sys, 'frozen', False): from multiprocessing.forking import freeze_support freeze_support() def get_logger(): ''' Return package logger -- if it does not already exist then it is created ''' from multiprocessing.util import get_logger return get_logger() def log_to_stderr(level=None): ''' Turn on logging and add a handler which prints to stderr ''' from multiprocessing.util import log_to_stderr return log_to_stderr(level) def allow_connection_pickling(): ''' Install support for sending connections and sockets between processes ''' from multiprocessing import reduction # # Definitions depending on native semaphores # def Lock(): ''' Returns a non-recursive lock object ''' from multiprocessing.synchronize import Lock return Lock() def RLock(): ''' Returns a recursive lock object ''' from multiprocessing.synchronize import RLock return RLock() def Condition(lock=None): ''' Returns a condition object ''' from multiprocessing.synchronize import Condition return Condition(lock) def Semaphore(value=1): ''' Returns a semaphore object ''' from multiprocessing.synchronize import Semaphore return Semaphore(value) def BoundedSemaphore(value=1): ''' Returns a bounded semaphore object ''' from multiprocessing.synchronize import BoundedSemaphore return BoundedSemaphore(value) def Event(): ''' Returns an event object ''' from multiprocessing.synchronize import Event return Event() def Queue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import Queue return Queue(maxsize) def JoinableQueue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import JoinableQueue return JoinableQueue(maxsize) def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None): ''' Returns a process pool object ''' from multiprocessing.pool import Pool return Pool(processes, initializer, initargs, maxtasksperchild) def RawValue(typecode_or_type, *args): ''' Returns a shared object ''' from multiprocessing.sharedctypes import RawValue return RawValue(typecode_or_type, *args) def RawArray(typecode_or_type, size_or_initializer): ''' Returns a shared array ''' from multiprocessing.sharedctypes import RawArray return RawArray(typecode_or_type, size_or_initializer) def Value(typecode_or_type, *args, **kwds): ''' Returns a synchronized shared object ''' from multiprocessing.sharedctypes import Value return Value(typecode_or_type, *args, **kwds) def Array(typecode_or_type, size_or_initializer, **kwds): ''' Returns a synchronized shared array ''' from multiprocessing.sharedctypes import Array return Array(typecode_or_type, size_or_initializer, **kwds) # # # if sys.platform == 'win32': def set_executable(executable): ''' Sets the path to a python.exe or pythonw.exe binary used to run child processes on Windows instead of sys.executable. Useful for people embedding Python. ''' from multiprocessing.forking import set_executable set_executable(executable) __all__ += ['set_executable']
comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0
conditional_block
test_custom_dm_diam_dm_proj.py
import shesha.config as conf simul_name = "bench_scao_sh_16x16_8pix" layout = "layoutDeFab_SH" # loop
p_loop.set_niter(1000) p_loop.set_ittime(0.002) # =1/500 # geom p_geom = conf.Param_geom() p_geom.set_zenithangle(0.) # tel p_tel = conf.Param_tel() p_tel.set_diam(4.0) p_tel.set_cobs(0.2) # atmos p_atmos = conf.Param_atmos() p_atmos.set_r0(0.16) p_atmos.set_nscreens(1) p_atmos.set_frac([1.0]) p_atmos.set_alt([0.0]) p_atmos.set_windspeed([10.]) p_atmos.set_winddir([45.]) p_atmos.set_L0([1.e5]) # target p_target = conf.Param_target() p_targets = [p_target] # p_target.set_ntargets(1) p_target.set_xpos(0.) p_target.set_ypos(0.) p_target.set_Lambda(1.65) p_target.set_mag(10.) # wfs p_wfs0 = conf.Param_wfs(roket=True) p_wfss = [p_wfs0] p_wfs0.set_type("sh") p_wfs0.set_nxsub(8) p_wfs0.set_npix(8) p_wfs0.set_pixsize(0.3) p_wfs0.set_fracsub(0.8) p_wfs0.set_xpos(0.) p_wfs0.set_ypos(0.) p_wfs0.set_Lambda(0.5) p_wfs0.set_gsmag(8.) p_wfs0.set_optthroughput(0.5) p_wfs0.set_zerop(1.e11) p_wfs0.set_noise(3.) p_wfs0.set_atmos_seen(1) # lgs parameters # p_wfs0.set_gsalt(90*1.e3) # p_wfs0.set_lltx(0) # p_wfs0.set_llty(0) # p_wfs0.set_laserpower(10) # p_wfs0.set_lgsreturnperwatt(1.e3) # p_wfs0.set_proftype("Exp") # p_wfs0.set_beamsize(0.8) # dm p_dm0 = conf.Param_dm() p_dm1 = conf.Param_dm() p_dms = [p_dm0, p_dm1] p_dm0.set_type("pzt") p_dm0.set_file_influ_fits("test_custom_dm.fits") p_dm0.set_alt(0.) p_dm0.set_thresh(0.3) p_dm0.set_unitpervolt(0.01) p_dm0.set_push4imat(100.) p_dm0.set_diam_dm_proj(4.1) p_dm1.set_type("tt") p_dm1.set_alt(0.) p_dm1.set_unitpervolt(0.0005) p_dm1.set_push4imat(10.) # centroiders p_centroider0 = conf.Param_centroider() p_centroiders = [p_centroider0] p_centroider0.set_nwfs(0) p_centroider0.set_type("cog") # p_centroider0.set_type("corr") # p_centroider0.set_type_fct("model") # controllers p_controller0 = conf.Param_controller() p_controllers = [p_controller0] p_controller0.set_type("ls") p_controller0.set_nwfs([0]) p_controller0.set_ndm([0, 1]) p_controller0.set_maxcond(1500.) p_controller0.set_delay(1.) p_controller0.set_gain(0.4) p_controller0.set_modopti(0) p_controller0.set_nrec(2048) p_controller0.set_nmodes(216) p_controller0.set_gmin(0.001) p_controller0.set_gmax(0.5) p_controller0.set_ngain(500)
p_loop = conf.Param_loop()
random_line_split
mpl_msk_spb.py
# -*- coding: utf-8 -*- # http://matplotlib.org/basemap/users/examples.html from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # create new figure, axes instances. fig=plt.figure() ax=fig.add_axes([0.1,0.1,0.8,0.8]) # setup mercator map projection. m = Basemap(llcrnrlon=0.,llcrnrlat=20.,urcrnrlon=80.,urcrnrlat=70.,\ rsphere=(6378137.00,6356752.3142),\ resolution='l',projection='merc',\ lat_0=55.,lon_0=37.,lat_ts=20.) # nylat, nylon are lat/lon of New York nylat = 55.7522200; nylon = 37.6155600 # lonlat, lonlon are lat/lon of London. lonlat = 59.9386300; lonlon = 30.3141300 # draw great circle route between NY and London m.drawgreatcircle(nylon,nylat,lonlon,lonlat,linewidth=2,color='b') m.drawcoastlines() m.fillcontinents() # draw parallels m.drawparallels(np.arange(-20,0,20),labels=[1,1,0,1])
# draw meridians m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1]) ax.set_title('Great Circle from New York to London') plt.show()
random_line_split
__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # Desarrollado por rNet Soluciones # Jefe de Proyecto: Ing. Ulises Tlatoani Vidal Rieder # Desarrollador: Ing. Salvador Daniel Pelayo Gómez. # Analista: Lic. David Padilla Bobadilla # ############################################################################## # # OpenERP, Open Source Management Solution # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. #
import report_cp
# You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ##############################################################################
random_line_split
sched.rs
//! Execution scheduling //! //! See Also //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] mod sched_linux_like { use crate::errno::Errno; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { /// The calling process and the child process run in the same /// memory space. CLONE_VM; /// The caller and the child process share the same filesystem /// information. CLONE_FS; /// The calling process and the child process share the same file /// descriptor table. CLONE_FILES; /// The calling process and the child process share the same table /// of signal handlers. CLONE_SIGHAND; /// If the calling process is being traced, then trace the child /// also. CLONE_PTRACE; /// The execution of the calling process is suspended until the /// child releases its virtual memory resources via a call to /// execve(2) or _exit(2) (as with vfork(2)). CLONE_VFORK; /// The parent of the new child (as returned by getppid(2)) /// will be the same as that of the calling process. CLONE_PARENT; /// The child is placed in the same thread group as the calling /// process. CLONE_THREAD; /// The cloned child is started in a new mount namespace. CLONE_NEWNS; /// The child and the calling process share a single list of System /// V semaphore adjustment values CLONE_SYSVSEM; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_SETTLS; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_PARENT_SETTID; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_CLEARTID; /// Unused since Linux 2.6.2 #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")] CLONE_DETACHED; /// A tracing process cannot force `CLONE_PTRACE` on this child /// process. CLONE_UNTRACED; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_SETTID; /// Create the process in a new cgroup namespace. CLONE_NEWCGROUP; /// Create the process in a new UTS namespace. CLONE_NEWUTS; /// Create the process in a new IPC namespace. CLONE_NEWIPC; /// Create the process in a new user namespace. CLONE_NEWUSER; /// Create the process in a new PID namespace. CLONE_NEWPID; /// Create the process in a new network namespace. CLONE_NEWNET; /// The new process shares an I/O context with the calling process. CLONE_IO; } } /// Type for the function executed by [`clone`]. pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and /// sched_getaffinity for example. /// /// This is a wrapper around `libc::cpu_set_t`. #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CpuSet { cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id to test pub fn is_set(&self, field: usize) -> Result<bool>
/// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) } } /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} Ok(()) } } /// Return the maximum number of CPU in CpuSet pub const fn count() -> usize { 8 * mem::size_of::<libc::cpu_set_t>() } } impl Default for CpuSet { fn default() -> Self { Self::new() } } /// `sched_setaffinity` set a thread's CPU affinity mask /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html)) /// /// `pid` is the thread ID to update. /// If pid is zero, then the calling thread is updated. /// /// The `cpuset` argument specifies the set of CPUs on which the thread /// will be eligible to run. /// /// # Example /// /// Binding the current thread to CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::{CpuSet, sched_setaffinity}; /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); /// cpu_set.set(0); /// sched_setaffinity(Pid::from_raw(0), &cpu_set); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { libc::sched_setaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &cpuset.cpu_set, ) }; Errno::result(res).map(drop) } /// `sched_getaffinity` get a thread's CPU affinity mask /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html)) /// /// `pid` is the thread ID to check. /// If pid is zero, then the calling thread is checked. /// /// Returned `cpuset` is the set of CPUs on which the thread /// is eligible to run. /// /// # Example /// /// Checking if the current thread can run on CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::sched_getaffinity; /// use nix::unistd::Pid; /// /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap(); /// if cpu_set.is_set(0).unwrap() { /// println!("Current thread can run on CPU 0"); /// } /// ``` pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> { let mut cpuset = CpuSet::new(); let res = unsafe { libc::sched_getaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &mut cpuset.cpu_set, ) }; Errno::result(res).and(Ok(cpuset)) } /// `clone` create a child process /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html)) /// /// `stack` is a reference to an array which will hold the stack of the new /// process. Unlike when calling `clone(2)` from C, the provided stack /// address need not be the highest address of the region. Nix will take /// care of that requirement. The user only needs to provide a reference to /// a normally allocated buffer. pub fn clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().add(stack.len()); let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, &mut cb as *mut _ as *mut c_void, ) }; Errno::result(res).map(Pid::from_raw) } /// disassociate parts of the process execution context /// /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html) pub fn unshare(flags: CloneFlags) -> Result<()> { let res = unsafe { libc::unshare(flags.bits()) }; Errno::result(res).map(drop) } /// reassociate thread with a namespace /// /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html) pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> { let res = unsafe { libc::setns(fd, nstype.bits()) }; Errno::result(res).map(drop) } } /// Explicitly yield the processor to other threads. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html) pub fn sched_yield() -> Result<()> { let res = unsafe { libc::sched_yield() }; Errno::result(res).map(drop) }
{ if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } }
identifier_body
sched.rs
//! Execution scheduling //! //! See Also //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] mod sched_linux_like { use crate::errno::Errno; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { /// The calling process and the child process run in the same /// memory space. CLONE_VM; /// The caller and the child process share the same filesystem /// information. CLONE_FS; /// The calling process and the child process share the same file /// descriptor table. CLONE_FILES; /// The calling process and the child process share the same table /// of signal handlers. CLONE_SIGHAND; /// If the calling process is being traced, then trace the child /// also. CLONE_PTRACE; /// The execution of the calling process is suspended until the /// child releases its virtual memory resources via a call to /// execve(2) or _exit(2) (as with vfork(2)). CLONE_VFORK; /// The parent of the new child (as returned by getppid(2)) /// will be the same as that of the calling process. CLONE_PARENT; /// The child is placed in the same thread group as the calling /// process. CLONE_THREAD; /// The cloned child is started in a new mount namespace. CLONE_NEWNS; /// The child and the calling process share a single list of System /// V semaphore adjustment values CLONE_SYSVSEM; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_SETTLS; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_PARENT_SETTID; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_CLEARTID; /// Unused since Linux 2.6.2 #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")] CLONE_DETACHED; /// A tracing process cannot force `CLONE_PTRACE` on this child /// process. CLONE_UNTRACED; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_SETTID; /// Create the process in a new cgroup namespace. CLONE_NEWCGROUP; /// Create the process in a new UTS namespace. CLONE_NEWUTS; /// Create the process in a new IPC namespace. CLONE_NEWIPC; /// Create the process in a new user namespace. CLONE_NEWUSER; /// Create the process in a new PID namespace. CLONE_NEWPID; /// Create the process in a new network namespace. CLONE_NEWNET; /// The new process shares an I/O context with the calling process. CLONE_IO; } } /// Type for the function executed by [`clone`]. pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and /// sched_getaffinity for example. /// /// This is a wrapper around `libc::cpu_set_t`. #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CpuSet { cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id to test pub fn is_set(&self, field: usize) -> Result<bool> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } } /// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else
} /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} Ok(()) } } /// Return the maximum number of CPU in CpuSet pub const fn count() -> usize { 8 * mem::size_of::<libc::cpu_set_t>() } } impl Default for CpuSet { fn default() -> Self { Self::new() } } /// `sched_setaffinity` set a thread's CPU affinity mask /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html)) /// /// `pid` is the thread ID to update. /// If pid is zero, then the calling thread is updated. /// /// The `cpuset` argument specifies the set of CPUs on which the thread /// will be eligible to run. /// /// # Example /// /// Binding the current thread to CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::{CpuSet, sched_setaffinity}; /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); /// cpu_set.set(0); /// sched_setaffinity(Pid::from_raw(0), &cpu_set); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { libc::sched_setaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &cpuset.cpu_set, ) }; Errno::result(res).map(drop) } /// `sched_getaffinity` get a thread's CPU affinity mask /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html)) /// /// `pid` is the thread ID to check. /// If pid is zero, then the calling thread is checked. /// /// Returned `cpuset` is the set of CPUs on which the thread /// is eligible to run. /// /// # Example /// /// Checking if the current thread can run on CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::sched_getaffinity; /// use nix::unistd::Pid; /// /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap(); /// if cpu_set.is_set(0).unwrap() { /// println!("Current thread can run on CPU 0"); /// } /// ``` pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> { let mut cpuset = CpuSet::new(); let res = unsafe { libc::sched_getaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &mut cpuset.cpu_set, ) }; Errno::result(res).and(Ok(cpuset)) } /// `clone` create a child process /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html)) /// /// `stack` is a reference to an array which will hold the stack of the new /// process. Unlike when calling `clone(2)` from C, the provided stack /// address need not be the highest address of the region. Nix will take /// care of that requirement. The user only needs to provide a reference to /// a normally allocated buffer. pub fn clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().add(stack.len()); let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, &mut cb as *mut _ as *mut c_void, ) }; Errno::result(res).map(Pid::from_raw) } /// disassociate parts of the process execution context /// /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html) pub fn unshare(flags: CloneFlags) -> Result<()> { let res = unsafe { libc::unshare(flags.bits()) }; Errno::result(res).map(drop) } /// reassociate thread with a namespace /// /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html) pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> { let res = unsafe { libc::setns(fd, nstype.bits()) }; Errno::result(res).map(drop) } } /// Explicitly yield the processor to other threads. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html) pub fn sched_yield() -> Result<()> { let res = unsafe { libc::sched_yield() }; Errno::result(res).map(drop) }
{ unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) }
conditional_block
sched.rs
//! Execution scheduling //! //! See Also //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] mod sched_linux_like { use crate::errno::Errno; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { /// The calling process and the child process run in the same /// memory space. CLONE_VM; /// The caller and the child process share the same filesystem /// information. CLONE_FS; /// The calling process and the child process share the same file /// descriptor table. CLONE_FILES; /// The calling process and the child process share the same table /// of signal handlers. CLONE_SIGHAND; /// If the calling process is being traced, then trace the child /// also. CLONE_PTRACE; /// The execution of the calling process is suspended until the /// child releases its virtual memory resources via a call to /// execve(2) or _exit(2) (as with vfork(2)). CLONE_VFORK; /// The parent of the new child (as returned by getppid(2)) /// will be the same as that of the calling process. CLONE_PARENT; /// The child is placed in the same thread group as the calling /// process. CLONE_THREAD; /// The cloned child is started in a new mount namespace. CLONE_NEWNS; /// The child and the calling process share a single list of System /// V semaphore adjustment values CLONE_SYSVSEM; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_SETTLS; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_PARENT_SETTID; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_CLEARTID; /// Unused since Linux 2.6.2 #[deprecated(since = "0.23.0", note = "Deprecated by Linux 2.6.2")] CLONE_DETACHED; /// A tracing process cannot force `CLONE_PTRACE` on this child /// process. CLONE_UNTRACED; // Not supported by Nix due to lack of varargs support in Rust FFI // CLONE_CHILD_SETTID; /// Create the process in a new cgroup namespace. CLONE_NEWCGROUP; /// Create the process in a new UTS namespace. CLONE_NEWUTS; /// Create the process in a new IPC namespace. CLONE_NEWIPC; /// Create the process in a new user namespace. CLONE_NEWUSER; /// Create the process in a new PID namespace. CLONE_NEWPID; /// Create the process in a new network namespace. CLONE_NEWNET; /// The new process shares an I/O context with the calling process. CLONE_IO; } } /// Type for the function executed by [`clone`]. pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and /// sched_getaffinity for example. /// /// This is a wrapper around `libc::cpu_set_t`. #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct
{ cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id to test pub fn is_set(&self, field: usize) -> Result<bool> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } } /// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) } } /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} Ok(()) } } /// Return the maximum number of CPU in CpuSet pub const fn count() -> usize { 8 * mem::size_of::<libc::cpu_set_t>() } } impl Default for CpuSet { fn default() -> Self { Self::new() } } /// `sched_setaffinity` set a thread's CPU affinity mask /// ([`sched_setaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_setaffinity.2.html)) /// /// `pid` is the thread ID to update. /// If pid is zero, then the calling thread is updated. /// /// The `cpuset` argument specifies the set of CPUs on which the thread /// will be eligible to run. /// /// # Example /// /// Binding the current thread to CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::{CpuSet, sched_setaffinity}; /// use nix::unistd::Pid; /// /// let mut cpu_set = CpuSet::new(); /// cpu_set.set(0); /// sched_setaffinity(Pid::from_raw(0), &cpu_set); /// ``` pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> { let res = unsafe { libc::sched_setaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &cpuset.cpu_set, ) }; Errno::result(res).map(drop) } /// `sched_getaffinity` get a thread's CPU affinity mask /// ([`sched_getaffinity(2)`](https://man7.org/linux/man-pages/man2/sched_getaffinity.2.html)) /// /// `pid` is the thread ID to check. /// If pid is zero, then the calling thread is checked. /// /// Returned `cpuset` is the set of CPUs on which the thread /// is eligible to run. /// /// # Example /// /// Checking if the current thread can run on CPU 0 can be done as follows: /// /// ```rust,no_run /// use nix::sched::sched_getaffinity; /// use nix::unistd::Pid; /// /// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap(); /// if cpu_set.is_set(0).unwrap() { /// println!("Current thread can run on CPU 0"); /// } /// ``` pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> { let mut cpuset = CpuSet::new(); let res = unsafe { libc::sched_getaffinity( pid.into(), mem::size_of::<CpuSet>() as libc::size_t, &mut cpuset.cpu_set, ) }; Errno::result(res).and(Ok(cpuset)) } /// `clone` create a child process /// ([`clone(2)`](https://man7.org/linux/man-pages/man2/clone.2.html)) /// /// `stack` is a reference to an array which will hold the stack of the new /// process. Unlike when calling `clone(2)` from C, the provided stack /// address need not be the highest address of the region. Nix will take /// care of that requirement. The user only needs to provide a reference to /// a normally allocated buffer. pub fn clone( mut cb: CloneCb, stack: &mut [u8], flags: CloneFlags, signal: Option<c_int>, ) -> Result<Pid> { extern "C" fn callback(data: *mut CloneCb) -> c_int { let cb: &mut CloneCb = unsafe { &mut *data }; (*cb)() as c_int } let res = unsafe { let combined = flags.bits() | signal.unwrap_or(0); let ptr = stack.as_mut_ptr().add(stack.len()); let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, &mut cb as *mut _ as *mut c_void, ) }; Errno::result(res).map(Pid::from_raw) } /// disassociate parts of the process execution context /// /// See also [unshare(2)](https://man7.org/linux/man-pages/man2/unshare.2.html) pub fn unshare(flags: CloneFlags) -> Result<()> { let res = unsafe { libc::unshare(flags.bits()) }; Errno::result(res).map(drop) } /// reassociate thread with a namespace /// /// See also [setns(2)](https://man7.org/linux/man-pages/man2/setns.2.html) pub fn setns(fd: RawFd, nstype: CloneFlags) -> Result<()> { let res = unsafe { libc::setns(fd, nstype.bits()) }; Errno::result(res).map(drop) } } /// Explicitly yield the processor to other threads. /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sched_yield.html) pub fn sched_yield() -> Result<()> { let res = unsafe { libc::sched_yield() }; Errno::result(res).map(drop) }
CpuSet
identifier_name
teamHandler.js
// Copyright 2015 rain1017. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. See the AUTHORS file // for names of contributors. 'use strict'; var P = require('quick-pomelo').Promise; var Handler = function(app){ this.app = app; }; var proto = Handler.prototype; proto.create = function(msg, session, next){ var opts = msg.opts; return this.app.controllers.team.createAsync(opts) .nodeify(next); }; proto.remove = function(msg, session, next){ var teamId = msg.teamId || session.uid; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.removeAsync(teamId) .nodeify(next); }; proto.join = function(msg, session, next){ var playerId = session.uid; var teamId = msg.teamId; if(!playerId || !teamId){ return next(new Error('playerId or teamId is missing')); } return this.app.controllers.team.joinAsync(teamId, playerId) .nodeify(next); }; proto.quit = function(msg, session, next){ var playerId = session.uid; var teamId = msg.teamId; if(!playerId || !teamId)
return this.app.controllers.team.quitAsync(teamId, playerId) .nodeify(next); }; proto.push = function(msg, session, next){ var teamId = msg.teamId; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.pushAsync(teamId, msg.playerIds, msg.route, msg.msg, msg.persistent) .nodeify(next); }; proto.getMsgs = function(msg, session, next){ var teamId = msg.teamId; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.getMsgsAsync(teamId, msg.seq, msg.count) .nodeify(next); }; module.exports = function(app){ return new Handler(app); };
{ return next(new Error('playerId or teamId is missing')); }
conditional_block
teamHandler.js
// Copyright 2015 rain1017. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. See the AUTHORS file // for names of contributors. 'use strict'; var P = require('quick-pomelo').Promise; var Handler = function(app){ this.app = app; }; var proto = Handler.prototype; proto.create = function(msg, session, next){ var opts = msg.opts; return this.app.controllers.team.createAsync(opts) .nodeify(next); }; proto.remove = function(msg, session, next){ var teamId = msg.teamId || session.uid; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.removeAsync(teamId) .nodeify(next); }; proto.join = function(msg, session, next){ var playerId = session.uid;
if(!playerId || !teamId){ return next(new Error('playerId or teamId is missing')); } return this.app.controllers.team.joinAsync(teamId, playerId) .nodeify(next); }; proto.quit = function(msg, session, next){ var playerId = session.uid; var teamId = msg.teamId; if(!playerId || !teamId){ return next(new Error('playerId or teamId is missing')); } return this.app.controllers.team.quitAsync(teamId, playerId) .nodeify(next); }; proto.push = function(msg, session, next){ var teamId = msg.teamId; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.pushAsync(teamId, msg.playerIds, msg.route, msg.msg, msg.persistent) .nodeify(next); }; proto.getMsgs = function(msg, session, next){ var teamId = msg.teamId; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.getMsgsAsync(teamId, msg.seq, msg.count) .nodeify(next); }; module.exports = function(app){ return new Handler(app); };
var teamId = msg.teamId;
random_line_split
roll-the-dice.py
## # @author Brandon Michael # Roll the dice based on the user's input. Track double rolls and display # the double totals. # import the random library import random # Set the start and end values the same as a dice start = 1 end = 6 # Set the running total for doubles found totalDoubles = 0 # Get the number of times we need to roll the dice rolls = int(input("Enter the number of dice rolls: ")) # Loop through the number of rolls for num in range(0, rolls, 1): # Capture the rolls to check for doubles roll_1 = random.randint(start, end) roll_2 = random.randint(start, end) # Check if rolls equal each other, and track the double count if roll_1 == roll_2:
else: print(roll_1, roll_2) # Print the results print(totalDoubles, "double(s) rolled.")
totalDoubles = totalDoubles + 1 print(roll_1, roll_2, "Double !")
conditional_block
roll-the-dice.py
## # @author Brandon Michael # Roll the dice based on the user's input. Track double rolls and display # the double totals. # import the random library import random # Set the start and end values the same as a dice start = 1 end = 6 # Set the running total for doubles found totalDoubles = 0 # Get the number of times we need to roll the dice rolls = int(input("Enter the number of dice rolls: ")) # Loop through the number of rolls for num in range(0, rolls, 1): # Capture the rolls to check for doubles
totalDoubles = totalDoubles + 1 print(roll_1, roll_2, "Double !") else: print(roll_1, roll_2) # Print the results print(totalDoubles, "double(s) rolled.")
roll_1 = random.randint(start, end) roll_2 = random.randint(start, end) # Check if rolls equal each other, and track the double count if roll_1 == roll_2:
random_line_split
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject'; export class ReduceOperator<T, R> implements Operator<T, R> { acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, acc?: R) { this.acc = acc; this.project = project; } call(subscriber: Subscriber<T>): Subscriber<T> { return new ReduceSubscriber(subscriber, this.project, this.acc); } } export class
<T, R> extends Subscriber<T> { acc: R; hasSeed: boolean; hasValue: boolean = false; project: (acc: R, x: T) => R; constructor(destination: Subscriber<T>, project: (acc: R, x: T) => R, acc?: R) { super(destination); this.acc = acc; this.project = project; this.hasSeed = typeof acc !== 'undefined'; } _next(x) { if (this.hasValue || (this.hasValue = this.hasSeed)) { const result = tryCatch(this.project).call(this, this.acc, x); if (result === errorObject) { this.destination.error(errorObject.e); } else { this.acc = result; } } else { this.acc = x; this.hasValue = true; } } _complete() { if (this.hasValue || this.hasSeed) { this.destination.next(this.acc); } this.destination.complete(); } }
ReduceSubscriber
identifier_name
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject'; export class ReduceOperator<T, R> implements Operator<T, R> { acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, acc?: R) { this.acc = acc; this.project = project; } call(subscriber: Subscriber<T>): Subscriber<T> { return new ReduceSubscriber(subscriber, this.project, this.acc); } } export class ReduceSubscriber<T, R> extends Subscriber<T> { acc: R; hasSeed: boolean; hasValue: boolean = false; project: (acc: R, x: T) => R; constructor(destination: Subscriber<T>, project: (acc: R, x: T) => R, acc?: R) { super(destination); this.acc = acc; this.project = project; this.hasSeed = typeof acc !== 'undefined'; } _next(x)
_complete() { if (this.hasValue || this.hasSeed) { this.destination.next(this.acc); } this.destination.complete(); } }
{ if (this.hasValue || (this.hasValue = this.hasSeed)) { const result = tryCatch(this.project).call(this, this.acc, x); if (result === errorObject) { this.destination.error(errorObject.e); } else { this.acc = result; } } else { this.acc = x; this.hasValue = true; } }
identifier_body
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject'; export class ReduceOperator<T, R> implements Operator<T, R> { acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, acc?: R) { this.acc = acc; this.project = project; } call(subscriber: Subscriber<T>): Subscriber<T> { return new ReduceSubscriber(subscriber, this.project, this.acc); } } export class ReduceSubscriber<T, R> extends Subscriber<T> { acc: R; hasSeed: boolean; hasValue: boolean = false; project: (acc: R, x: T) => R; constructor(destination: Subscriber<T>, project: (acc: R, x: T) => R, acc?: R) { super(destination); this.acc = acc; this.project = project; this.hasSeed = typeof acc !== 'undefined'; } _next(x) { if (this.hasValue || (this.hasValue = this.hasSeed)) { const result = tryCatch(this.project).call(this, this.acc, x); if (result === errorObject) { this.destination.error(errorObject.e); } else { this.acc = result; } } else { this.acc = x; this.hasValue = true; } } _complete() { if (this.hasValue || this.hasSeed)
this.destination.complete(); } }
{ this.destination.next(this.acc); }
conditional_block
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject';
acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, acc?: R) { this.acc = acc; this.project = project; } call(subscriber: Subscriber<T>): Subscriber<T> { return new ReduceSubscriber(subscriber, this.project, this.acc); } } export class ReduceSubscriber<T, R> extends Subscriber<T> { acc: R; hasSeed: boolean; hasValue: boolean = false; project: (acc: R, x: T) => R; constructor(destination: Subscriber<T>, project: (acc: R, x: T) => R, acc?: R) { super(destination); this.acc = acc; this.project = project; this.hasSeed = typeof acc !== 'undefined'; } _next(x) { if (this.hasValue || (this.hasValue = this.hasSeed)) { const result = tryCatch(this.project).call(this, this.acc, x); if (result === errorObject) { this.destination.error(errorObject.e); } else { this.acc = result; } } else { this.acc = x; this.hasValue = true; } } _complete() { if (this.hasValue || this.hasSeed) { this.destination.next(this.acc); } this.destination.complete(); } }
export class ReduceOperator<T, R> implements Operator<T, R> {
random_line_split
checkbox.type.spec.ts
import { FormlyFieldConfig } from '@ngx-formly/core'; import { createFieldComponent, ɵCustomEvent } from '@ngx-formly/core/testing'; import { FormlyNzCheckboxModule } from '@ngx-formly/ng-zorro-antd/checkbox'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; const renderComponent = (field: FormlyFieldConfig) => { return createFieldComponent(field, { imports: [NoopAnimationsModule, FormlyNzCheckboxModule], }); }; describe('ui-ng-zorro-antd: Checkbox Type', () => { it('should render checkbox type', () => { const { query } = renderComponent({ key: 'name', type: 'checkbox', }); expect(query('formly-wrapper-nz-form-field')).not.toBeNull(); expect(query('.ant-checkbox-indeterminate')).not.toBeNull(); expect(query('input[type="checkbox"]')).not.toBeNull(); const { attributes } = query('label[nz-checkbox]'); expect(attributes).toMatchObject({ id: 'formly_1_checkbox_name_0',
}); }); it('should render boolean type', () => { const { query } = renderComponent({ key: 'name', type: 'boolean', }); expect(query('formly-wrapper-nz-form-field')).not.toBeNull(); expect(query('.ant-checkbox-indeterminate')).not.toBeNull(); expect(query('input[type="checkbox"]')).not.toBeNull(); const { attributes } = query('label[nz-checkbox]'); expect(attributes).toMatchObject({ id: 'formly_1_boolean_name_0', }); }); it('should bind control value on change', () => { const changeSpy = jest.fn(); const { query, field, detectChanges } = renderComponent({ key: 'name', type: 'checkbox', templateOptions: { change: changeSpy }, }); const inputDebugEl = query<HTMLInputElement>('input[type="checkbox"]'); inputDebugEl.triggerEventHandler('change', ɵCustomEvent({ checked: true })); detectChanges(); expect(field.formControl.value).toBeTrue(); expect(changeSpy).toHaveBeenCalledOnce(); inputDebugEl.triggerEventHandler('change', ɵCustomEvent({ checked: false })); detectChanges(); expect(field.formControl.value).toBeFalse(); expect(changeSpy).toHaveBeenCalledTimes(2); }); });
random_line_split
SmoothScroll.js
// SmoothScroll v1.2.1 // Licensed under the terms of the MIT license. // People involved // - Balazs Galambosi (maintainer) // - Patrick Brunner (original idea) // - Michael Herf (Pulse Algorithm) // - Justin Force (Resurect) if (navigator.appVersion.indexOf("Mac") == -1) { // Scroll Variables (tweakable) var framerate = 150; // [Hz] var animtime = 500; // [px] var stepsize = 150; // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" var pulseAlgorithm = true; var pulseScale = 8; var pulseNormalize = 1; // Acceleration var acceleration = true; var accelDelta = 10; // 20 var accelMax = 1; // 1 // Keyboard Settings var keyboardsupport = true; // option var disableKeyboard = false; // other reasons var arrowscroll = 50; // [px] // Excluded pages var exclude = ""; var disabled = false; // Other Variables var frame = false; var direction = { x: 0, y: 0 }; var initdone = false; var fixedback = true; var root = document.documentElement; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initdone = true; // Checks if this script is running in a frame if (top != self) { frame = true; } /** * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { // DOMChange (throttle): fix height var pending = false; var refresh = function() { if (!pending && html.scrollHeight != document.height) { pending = true; // add a new pending action setTimeout(function(){ html.style.height = document.height + 'px'; pending = false; }, 500); // act rarely to stay fast } }; html.style.height = ''; setTimeout(refresh, 10); addEvent("DOMNodeInserted", refresh); addEvent("DOMNodeRemoved", refresh); // clearfix if (root.offsetHeight <= windowHeight) { var underlay = document.createElement("div"); underlay.style.clear = "both"; body.appendChild(underlay); } } // gmail performance fix if (document.URL.indexOf("mail.google.com") > -1) { var s = document.createElement("style"); s.innerHTML = ".iu { visibility: hidden }"; (document.getElementsByTagName("head")[0] || html).appendChild(s); } // disable fixed background if (!fixedback && !disabled) { body.style.backgroundAttachment = "scroll"; html.style.backgroundAttachment = "scroll"; } } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = +new Date; /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top, delay) { delay || (delay = 1000); directionCheck(left, top); if (acceleration) { var now = +new Date; var elapsed = now - lastScroll; if (elapsed < accelDelta) { var factor = (1 + (30 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, accelMax); left *= factor; top *= factor; } } lastScroll = +new Date; } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: +new Date }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function() { var now = +new Date; var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= animtime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / animtime; // easing [optional] if (pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY) } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (delay / framerate + 1)); } else { pending = false; } } // start a new queue of actions requestFrame(step, elem, 0); pending = true; } /*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initdone) { init(); } var target = event.target; var overflowing = overflowingAncestor(target); // use default if there's no overflowing // element or default action is prevented if (!overflowing || event.defaultPrevented || isNodeName(activeElement, "embed") ||
var deltaX = event.wheelDeltaX || 0; var deltaY = event.wheelDeltaY || 0; // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = event.wheelDelta || 0; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= stepsize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= stepsize / 120; } scrollArray(overflowing, -deltaX, -deltaY); event.preventDefault(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown if ( /input|textarea|select|embed/i.test(target.nodeName) || target.isContentEditable || event.defaultPrevented || modifier ) { return true; } // spacebar should trigger button press if (isNodeName(target, "button") && event.keyCode === key.spacebar) { return true; } var shift, x = 0, y = 0; var elem = overflowingAncestor(activeElement); var clientHeight = elem.clientHeight; if (elem == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -arrowscroll; break; case key.down: y = arrowscroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -elem.scrollTop; break; case key.end: var damt = elem.scrollHeight - elem.scrollTop - clientHeight; y = (damt > 0) ? damt+10 : 0; break; case key.left: x = -arrowscroll; break; case key.right: x = arrowscroll; break; default: return true; // a key we don't care about } scrollArray(elem, x, y); event.preventDefault(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var cache = {}; // cleared out every once in while setInterval(function(){ cache = {}; }, 10 * 1000); var uniqueID = (function() { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } function overflowingAncestor(el) { var elems = []; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { if (!frame || root.clientHeight + 10 < rootScrollHeight) { return setCache(elems, document.body); // scrolling root in WebKit } } else if (el.clientHeight + 10 < el.scrollHeight) { overflow = getComputedStyle(el, "").getPropertyValue("overflow-y"); if (overflow === "scroll" || overflow === "auto") { return setCache(elems, el); } } } while (el = el.parentNode); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn, bubble) { window.addEventListener(type, fn, (bubble||false)); } function removeEvent(type, fn, bubble) { window.removeEventListener(type, fn, (bubble||false)); } function isNodeName(el, tag) { return (el.nodeName||"").toLowerCase() === tag.toLowerCase(); } function directionCheck(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var requestFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(callback, element, delay){ window.setTimeout(callback, delay || (1000/60)); }; })(); /*********************************************** * PULSE ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (pulseNormalize == 1) { pulseNormalize /= pulse_(1); } return pulse_(x); } addEvent("mousedown", mousedown); addEvent("mousewheel", wheel); addEvent("load", init); }
(isNodeName(target, "embed") && /\.pdf/i.test(target.src))) { return true; }
random_line_split
SmoothScroll.js
// SmoothScroll v1.2.1 // Licensed under the terms of the MIT license. // People involved // - Balazs Galambosi (maintainer) // - Patrick Brunner (original idea) // - Michael Herf (Pulse Algorithm) // - Justin Force (Resurect) if (navigator.appVersion.indexOf("Mac") == -1) { // Scroll Variables (tweakable) var framerate = 150; // [Hz] var animtime = 500; // [px] var stepsize = 150; // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" var pulseAlgorithm = true; var pulseScale = 8; var pulseNormalize = 1; // Acceleration var acceleration = true; var accelDelta = 10; // 20 var accelMax = 1; // 1 // Keyboard Settings var keyboardsupport = true; // option var disableKeyboard = false; // other reasons var arrowscroll = 50; // [px] // Excluded pages var exclude = ""; var disabled = false; // Other Variables var frame = false; var direction = { x: 0, y: 0 }; var initdone = false; var fixedback = true; var root = document.documentElement; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initdone = true; // Checks if this script is running in a frame if (top != self) { frame = true; } /** * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { // DOMChange (throttle): fix height var pending = false; var refresh = function() { if (!pending && html.scrollHeight != document.height) { pending = true; // add a new pending action setTimeout(function(){ html.style.height = document.height + 'px'; pending = false; }, 500); // act rarely to stay fast } }; html.style.height = ''; setTimeout(refresh, 10); addEvent("DOMNodeInserted", refresh); addEvent("DOMNodeRemoved", refresh); // clearfix if (root.offsetHeight <= windowHeight) { var underlay = document.createElement("div"); underlay.style.clear = "both"; body.appendChild(underlay); } } // gmail performance fix if (document.URL.indexOf("mail.google.com") > -1) { var s = document.createElement("style"); s.innerHTML = ".iu { visibility: hidden }"; (document.getElementsByTagName("head")[0] || html).appendChild(s); } // disable fixed background if (!fixedback && !disabled) { body.style.backgroundAttachment = "scroll"; html.style.backgroundAttachment = "scroll"; } } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = +new Date; /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top, delay) { delay || (delay = 1000); directionCheck(left, top); if (acceleration) { var now = +new Date; var elapsed = now - lastScroll; if (elapsed < accelDelta) { var factor = (1 + (30 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, accelMax); left *= factor; top *= factor; } } lastScroll = +new Date; } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: +new Date }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function() { var now = +new Date; var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= animtime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / animtime; // easing [optional] if (pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY) } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (delay / framerate + 1)); } else { pending = false; } } // start a new queue of actions requestFrame(step, elem, 0); pending = true; } /*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initdone) { init(); } var target = event.target; var overflowing = overflowingAncestor(target); // use default if there's no overflowing // element or default action is prevented if (!overflowing || event.defaultPrevented || isNodeName(activeElement, "embed") || (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) { return true; } var deltaX = event.wheelDeltaX || 0; var deltaY = event.wheelDeltaY || 0; // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY)
// scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= stepsize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= stepsize / 120; } scrollArray(overflowing, -deltaX, -deltaY); event.preventDefault(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown if ( /input|textarea|select|embed/i.test(target.nodeName) || target.isContentEditable || event.defaultPrevented || modifier ) { return true; } // spacebar should trigger button press if (isNodeName(target, "button") && event.keyCode === key.spacebar) { return true; } var shift, x = 0, y = 0; var elem = overflowingAncestor(activeElement); var clientHeight = elem.clientHeight; if (elem == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -arrowscroll; break; case key.down: y = arrowscroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -elem.scrollTop; break; case key.end: var damt = elem.scrollHeight - elem.scrollTop - clientHeight; y = (damt > 0) ? damt+10 : 0; break; case key.left: x = -arrowscroll; break; case key.right: x = arrowscroll; break; default: return true; // a key we don't care about } scrollArray(elem, x, y); event.preventDefault(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var cache = {}; // cleared out every once in while setInterval(function(){ cache = {}; }, 10 * 1000); var uniqueID = (function() { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } function overflowingAncestor(el) { var elems = []; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { if (!frame || root.clientHeight + 10 < rootScrollHeight) { return setCache(elems, document.body); // scrolling root in WebKit } } else if (el.clientHeight + 10 < el.scrollHeight) { overflow = getComputedStyle(el, "").getPropertyValue("overflow-y"); if (overflow === "scroll" || overflow === "auto") { return setCache(elems, el); } } } while (el = el.parentNode); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn, bubble) { window.addEventListener(type, fn, (bubble||false)); } function removeEvent(type, fn, bubble) { window.removeEventListener(type, fn, (bubble||false)); } function isNodeName(el, tag) { return (el.nodeName||"").toLowerCase() === tag.toLowerCase(); } function directionCheck(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var requestFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(callback, element, delay){ window.setTimeout(callback, delay || (1000/60)); }; })(); /*********************************************** * PULSE ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (pulseNormalize == 1) { pulseNormalize /= pulse_(1); } return pulse_(x); } addEvent("mousedown", mousedown); addEvent("mousewheel", wheel); addEvent("load", init); }
{ deltaY = event.wheelDelta || 0; }
conditional_block
SmoothScroll.js
// SmoothScroll v1.2.1 // Licensed under the terms of the MIT license. // People involved // - Balazs Galambosi (maintainer) // - Patrick Brunner (original idea) // - Michael Herf (Pulse Algorithm) // - Justin Force (Resurect) if (navigator.appVersion.indexOf("Mac") == -1) { // Scroll Variables (tweakable) var framerate = 150; // [Hz] var animtime = 500; // [px] var stepsize = 150; // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" var pulseAlgorithm = true; var pulseScale = 8; var pulseNormalize = 1; // Acceleration var acceleration = true; var accelDelta = 10; // 20 var accelMax = 1; // 1 // Keyboard Settings var keyboardsupport = true; // option var disableKeyboard = false; // other reasons var arrowscroll = 50; // [px] // Excluded pages var exclude = ""; var disabled = false; // Other Variables var frame = false; var direction = { x: 0, y: 0 }; var initdone = false; var fixedback = true; var root = document.documentElement; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initdone = true; // Checks if this script is running in a frame if (top != self) { frame = true; } /** * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { // DOMChange (throttle): fix height var pending = false; var refresh = function() { if (!pending && html.scrollHeight != document.height) { pending = true; // add a new pending action setTimeout(function(){ html.style.height = document.height + 'px'; pending = false; }, 500); // act rarely to stay fast } }; html.style.height = ''; setTimeout(refresh, 10); addEvent("DOMNodeInserted", refresh); addEvent("DOMNodeRemoved", refresh); // clearfix if (root.offsetHeight <= windowHeight) { var underlay = document.createElement("div"); underlay.style.clear = "both"; body.appendChild(underlay); } } // gmail performance fix if (document.URL.indexOf("mail.google.com") > -1) { var s = document.createElement("style"); s.innerHTML = ".iu { visibility: hidden }"; (document.getElementsByTagName("head")[0] || html).appendChild(s); } // disable fixed background if (!fixedback && !disabled) { body.style.backgroundAttachment = "scroll"; html.style.backgroundAttachment = "scroll"; } } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = +new Date; /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top, delay) { delay || (delay = 1000); directionCheck(left, top); if (acceleration) { var now = +new Date; var elapsed = now - lastScroll; if (elapsed < accelDelta) { var factor = (1 + (30 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, accelMax); left *= factor; top *= factor; } } lastScroll = +new Date; } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: +new Date }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function() { var now = +new Date; var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= animtime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / animtime; // easing [optional] if (pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY) } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (delay / framerate + 1)); } else { pending = false; } } // start a new queue of actions requestFrame(step, elem, 0); pending = true; } /*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initdone) { init(); } var target = event.target; var overflowing = overflowingAncestor(target); // use default if there's no overflowing // element or default action is prevented if (!overflowing || event.defaultPrevented || isNodeName(activeElement, "embed") || (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) { return true; } var deltaX = event.wheelDeltaX || 0; var deltaY = event.wheelDeltaY || 0; // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = event.wheelDelta || 0; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= stepsize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= stepsize / 120; } scrollArray(overflowing, -deltaX, -deltaY); event.preventDefault(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown if ( /input|textarea|select|embed/i.test(target.nodeName) || target.isContentEditable || event.defaultPrevented || modifier ) { return true; } // spacebar should trigger button press if (isNodeName(target, "button") && event.keyCode === key.spacebar) { return true; } var shift, x = 0, y = 0; var elem = overflowingAncestor(activeElement); var clientHeight = elem.clientHeight; if (elem == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -arrowscroll; break; case key.down: y = arrowscroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -elem.scrollTop; break; case key.end: var damt = elem.scrollHeight - elem.scrollTop - clientHeight; y = (damt > 0) ? damt+10 : 0; break; case key.left: x = -arrowscroll; break; case key.right: x = arrowscroll; break; default: return true; // a key we don't care about } scrollArray(elem, x, y); event.preventDefault(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var cache = {}; // cleared out every once in while setInterval(function(){ cache = {}; }, 10 * 1000); var uniqueID = (function() { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } function overflowingAncestor(el) { var elems = []; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { if (!frame || root.clientHeight + 10 < rootScrollHeight) { return setCache(elems, document.body); // scrolling root in WebKit } } else if (el.clientHeight + 10 < el.scrollHeight) { overflow = getComputedStyle(el, "").getPropertyValue("overflow-y"); if (overflow === "scroll" || overflow === "auto") { return setCache(elems, el); } } } while (el = el.parentNode); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn, bubble) { window.addEventListener(type, fn, (bubble||false)); } function removeEvent(type, fn, bubble) { window.removeEventListener(type, fn, (bubble||false)); } function isNodeName(el, tag) { return (el.nodeName||"").toLowerCase() === tag.toLowerCase(); } function
(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var requestFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(callback, element, delay){ window.setTimeout(callback, delay || (1000/60)); }; })(); /*********************************************** * PULSE ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (pulseNormalize == 1) { pulseNormalize /= pulse_(1); } return pulse_(x); } addEvent("mousedown", mousedown); addEvent("mousewheel", wheel); addEvent("load", init); }
directionCheck
identifier_name
SmoothScroll.js
// SmoothScroll v1.2.1 // Licensed under the terms of the MIT license. // People involved // - Balazs Galambosi (maintainer) // - Patrick Brunner (original idea) // - Michael Herf (Pulse Algorithm) // - Justin Force (Resurect) if (navigator.appVersion.indexOf("Mac") == -1) { // Scroll Variables (tweakable) var framerate = 150; // [Hz] var animtime = 500; // [px] var stepsize = 150; // [px] // Pulse (less tweakable) // ratio of "tail" to "acceleration" var pulseAlgorithm = true; var pulseScale = 8; var pulseNormalize = 1; // Acceleration var acceleration = true; var accelDelta = 10; // 20 var accelMax = 1; // 1 // Keyboard Settings var keyboardsupport = true; // option var disableKeyboard = false; // other reasons var arrowscroll = 50; // [px] // Excluded pages var exclude = ""; var disabled = false; // Other Variables var frame = false; var direction = { x: 0, y: 0 }; var initdone = false; var fixedback = true; var root = document.documentElement; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = document.documentElement; var windowHeight = window.innerHeight; var scrollHeight = body.scrollHeight; // check compat mode for root element root = (document.compatMode.indexOf('CSS') >= 0) ? html : body; activeElement = body; initdone = true; // Checks if this script is running in a frame if (top != self) { frame = true; } /** * This fixes a bug where the areas left and right to * the content does not trigger the onmousewheel event * on some pages. e.g.: html, body { height: 100% } */ else if (scrollHeight > windowHeight && (body.offsetHeight <= windowHeight || html.offsetHeight <= windowHeight)) { // DOMChange (throttle): fix height var pending = false; var refresh = function() { if (!pending && html.scrollHeight != document.height) { pending = true; // add a new pending action setTimeout(function(){ html.style.height = document.height + 'px'; pending = false; }, 500); // act rarely to stay fast } }; html.style.height = ''; setTimeout(refresh, 10); addEvent("DOMNodeInserted", refresh); addEvent("DOMNodeRemoved", refresh); // clearfix if (root.offsetHeight <= windowHeight) { var underlay = document.createElement("div"); underlay.style.clear = "both"; body.appendChild(underlay); } } // gmail performance fix if (document.URL.indexOf("mail.google.com") > -1) { var s = document.createElement("style"); s.innerHTML = ".iu { visibility: hidden }"; (document.getElementsByTagName("head")[0] || html).appendChild(s); } // disable fixed background if (!fixedback && !disabled) { body.style.backgroundAttachment = "scroll"; html.style.backgroundAttachment = "scroll"; } } /************************************************ * SCROLLING ************************************************/ var que = []; var pending = false; var lastScroll = +new Date; /** * Pushes scroll actions to the scrolling queue. */ function scrollArray(elem, left, top, delay)
/*********************************************** * EVENTS ***********************************************/ /** * Mouse wheel handler. * @param {Object} event */ function wheel(event) { if (!initdone) { init(); } var target = event.target; var overflowing = overflowingAncestor(target); // use default if there's no overflowing // element or default action is prevented if (!overflowing || event.defaultPrevented || isNodeName(activeElement, "embed") || (isNodeName(target, "embed") && /\.pdf/i.test(target.src))) { return true; } var deltaX = event.wheelDeltaX || 0; var deltaY = event.wheelDeltaY || 0; // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = event.wheelDelta || 0; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= stepsize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= stepsize / 120; } scrollArray(overflowing, -deltaX, -deltaY); event.preventDefault(); } /** * Keydown event handler. * @param {Object} event */ function keydown(event) { var target = event.target; var modifier = event.ctrlKey || event.altKey || event.metaKey || (event.shiftKey && event.keyCode !== key.spacebar); // do nothing if user is editing text // or using a modifier key (except shift) // or in a dropdown if ( /input|textarea|select|embed/i.test(target.nodeName) || target.isContentEditable || event.defaultPrevented || modifier ) { return true; } // spacebar should trigger button press if (isNodeName(target, "button") && event.keyCode === key.spacebar) { return true; } var shift, x = 0, y = 0; var elem = overflowingAncestor(activeElement); var clientHeight = elem.clientHeight; if (elem == document.body) { clientHeight = window.innerHeight; } switch (event.keyCode) { case key.up: y = -arrowscroll; break; case key.down: y = arrowscroll; break; case key.spacebar: // (+ shift) shift = event.shiftKey ? 1 : -1; y = -shift * clientHeight * 0.9; break; case key.pageup: y = -clientHeight * 0.9; break; case key.pagedown: y = clientHeight * 0.9; break; case key.home: y = -elem.scrollTop; break; case key.end: var damt = elem.scrollHeight - elem.scrollTop - clientHeight; y = (damt > 0) ? damt+10 : 0; break; case key.left: x = -arrowscroll; break; case key.right: x = arrowscroll; break; default: return true; // a key we don't care about } scrollArray(elem, x, y); event.preventDefault(); } /** * Mousedown event only for updating activeElement */ function mousedown(event) { activeElement = event.target; } /*********************************************** * OVERFLOW ***********************************************/ var cache = {}; // cleared out every once in while setInterval(function(){ cache = {}; }, 10 * 1000); var uniqueID = (function() { var i = 0; return function (el) { return el.uniqueID || (el.uniqueID = i++); }; })(); function setCache(elems, overflowing) { for (var i = elems.length; i--;) cache[uniqueID(elems[i])] = overflowing; return overflowing; } function overflowingAncestor(el) { var elems = []; var rootScrollHeight = root.scrollHeight; do { var cached = cache[uniqueID(el)]; if (cached) { return setCache(elems, cached); } elems.push(el); if (rootScrollHeight === el.scrollHeight) { if (!frame || root.clientHeight + 10 < rootScrollHeight) { return setCache(elems, document.body); // scrolling root in WebKit } } else if (el.clientHeight + 10 < el.scrollHeight) { overflow = getComputedStyle(el, "").getPropertyValue("overflow-y"); if (overflow === "scroll" || overflow === "auto") { return setCache(elems, el); } } } while (el = el.parentNode); } /*********************************************** * HELPERS ***********************************************/ function addEvent(type, fn, bubble) { window.addEventListener(type, fn, (bubble||false)); } function removeEvent(type, fn, bubble) { window.removeEventListener(type, fn, (bubble||false)); } function isNodeName(el, tag) { return (el.nodeName||"").toLowerCase() === tag.toLowerCase(); } function directionCheck(x, y) { x = (x > 0) ? 1 : -1; y = (y > 0) ? 1 : -1; if (direction.x !== x || direction.y !== y) { direction.x = x; direction.y = y; que = []; lastScroll = 0; } } var requestFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(callback, element, delay){ window.setTimeout(callback, delay || (1000/60)); }; })(); /*********************************************** * PULSE ***********************************************/ /** * Viscous fluid with a pulse for part and decay for the rest. * - Applies a fixed force over an interval (a damped acceleration), and * - Lets the exponential bleed away the velocity over a longer interval * - Michael Herf, http://stereopsis.com/stopping/ */ function pulse_(x) { var val, start, expx; // test x = x * pulseScale; if (x < 1) { // acceleartion val = x - (1 - Math.exp(-x)); } else { // tail // the previous animation ended here: start = Math.exp(-1); // simple viscous drag x -= 1; expx = 1 - Math.exp(-x); val = start + (expx * (1 - start)); } return val * pulseNormalize; } function pulse(x) { if (x >= 1) return 1; if (x <= 0) return 0; if (pulseNormalize == 1) { pulseNormalize /= pulse_(1); } return pulse_(x); } addEvent("mousedown", mousedown); addEvent("mousewheel", wheel); addEvent("load", init); }
{ delay || (delay = 1000); directionCheck(left, top); if (acceleration) { var now = +new Date; var elapsed = now - lastScroll; if (elapsed < accelDelta) { var factor = (1 + (30 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, accelMax); left *= factor; top *= factor; } } lastScroll = +new Date; } // push a scroll command que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: +new Date }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function() { var now = +new Date; var scrollX = 0; var scrollY = 0; for (var i = 0; i < que.length; i++) { var item = que[i]; var elapsed = now - item.start; var finished = (elapsed >= animtime); // scroll position: [0, 1] var position = (finished) ? 1 : elapsed / animtime; // easing [optional] if (pulseAlgorithm) { position = pulse(position); } // only need the difference var x = (item.x * position - item.lastX) >> 0; var y = (item.y * position - item.lastY) >> 0; // add this to the total scrolling scrollX += x; scrollY += y; // update last values item.lastX += x; item.lastY += y; // delete and step back if it's over if (finished) { que.splice(i, 1); i--; } } // scroll left and top if (scrollWindow) { window.scrollBy(scrollX, scrollY) } else { if (scrollX) elem.scrollLeft += scrollX; if (scrollY) elem.scrollTop += scrollY; } // clean up if there's nothing left to do if (!left && !top) { que = []; } if (que.length) { requestFrame(step, elem, (delay / framerate + 1)); } else { pending = false; } } // start a new queue of actions requestFrame(step, elem, 0); pending = true; }
identifier_body
async-gen-dstr-const-obj-ptrn-id-init-fn-name-cover.js
// This file was procedurally generated from the following sources: // - src/dstr-binding-for-await/obj-ptrn-id-init-fn-name-cover.case // - src/dstr-binding-for-await/default/for-await-of-async-gen-const.template /*--- description: SingleNameBinding assigns `name` to "anonymous" functions "through" cover grammar (for-await-of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation features: [destructuring-binding, async-iteration]
for await ( ForDeclaration of AssignmentExpression ) Statement [...] 2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet, async). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 4. Let destructuring be IsDestructuring of lhs. [...] 6. Repeat [...] j. If destructuring is false, then [...] k. Else i. If lhsKind is assignment, then [...] ii. Else if lhsKind is varBinding, then [...] iii. Else, 1. Assert: lhsKind is lexicalBinding. 2. Assert: lhs is a ForDeclaration. 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializer_opt [...] 6. If Initializer is present and v is undefined, then [...] d. If IsAnonymousFunctionDefinition(Initializer) is true, then i. Let hasNameProperty be HasOwnProperty(v, "name"). ii. ReturnIfAbrupt(hasNameProperty). iii. If hasNameProperty is false, perform SetFunctionName(v, bindingId). ---*/ var iterCount = 0; async function *fn() { for await (const { cover = (function () {}), xCover = (0, function() {}) } of [{}]) { assert.sameValue(cover.name, 'cover'); assert.notSameValue(xCover.name, 'xCover'); iterCount += 1; } } fn().next() .then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE) .then($DONE, $DONE);
flags: [generated, async] info: | IterationStatement :
random_line_split
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T>
/// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn default() -> Rawlink<T> { Rawlink::none() } }
{ unsafe { mem::transmute(self.p.as_ref()) } }
identifier_body
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T> { unsafe { mem::transmute(self.p.as_ref()) } } /// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() {
None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn default() -> Rawlink<T> { Rawlink::none() } }
random_line_split
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T> { unsafe { mem::transmute(self.p.as_ref()) } } /// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn
() -> Rawlink<T> { Rawlink::none() } }
default
identifier_name
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License // along with Intrusive. If not, see <http://www.gnu.org/licenses/>. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[cfg(all(feature="nostd",not(test)))] use core::prelude::*; use std::mem; use std::ptr; #[allow(raw_pointer_derive)] #[derive(Debug)] pub struct Rawlink<T> { p: *mut T } impl<T> Copy for Rawlink<T> {} unsafe impl<T:'static+Send> Send for Rawlink<T> {} unsafe impl<T:Send+Sync> Sync for Rawlink<T> {} /// Rawlink is a type like Option<T> but for holding a raw pointer impl<T> Rawlink<T> { /// Like Option::None for Rawlink pub fn none() -> Rawlink<T> { Rawlink{p: ptr::null_mut()} } /// Like Option::Some for Rawlink pub fn some(n: &mut T) -> Rawlink<T> { Rawlink{p: n} } /// Convert the `Rawlink` into an Option value pub fn resolve<'a>(&self) -> Option<&'a T> { unsafe { mem::transmute(self.p.as_ref()) } } /// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else
} /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Rawlink<T> { #[inline] fn clone(&self) -> Rawlink<T> { Rawlink{p: self.p} } } impl<T> Default for Rawlink<T> { fn default() -> Rawlink<T> { Rawlink::none() } }
{ Some(unsafe { mem::transmute(self.p) }) }
conditional_block
local-storage.d.ts
import { StorageEngine } from './storage'; /** * @name LocalStorage * @description * The LocalStorage storage engine uses the browser's local storage system for * storing key/value pairs. * * Note: LocalStorage should ONLY be used for temporary data that you can afford to lose. * Given disk space constraints on a mobile device, local storage might be "cleaned up" * by the operating system (iOS). * * For guaranteed, long-term storage, use the SqlStorage engine which stores data in a file. * * @usage * ```ts * import {Page, Storage, LocalStorage} from 'ionic-angular'; * @Page({ * template: `<ion-content></ion-content>` * }); * export class MyClass{ * constructor(){ * this.local = new Storage(LocalStorage); * this.local.set('didTutorial', 'true'); * } *} *``` * @demo /docs/v2/demos/local-storage/ * @see {@link /docs/v2/platform/storage/ Storage Platform Docs} */ export declare class
extends StorageEngine { constructor(options?: {}); /** * Get the value of a key in LocalStorage * @param {string} key the key you want to lookup in LocalStorage */ get(key: string): Promise<string>; /** * Set a key value pair and save it to LocalStorage * @param {string} key the key you want to save to LocalStorage * @param {string} value the value of the key you're saving */ set(key: string, value: string): Promise<any>; /** * Remove a key from LocalStorage * @param {string} key the key you want to remove from LocalStorage */ remove(key: string): Promise<any>; clear(): Promise<any>; }
LocalStorage
identifier_name
local-storage.d.ts
import { StorageEngine } from './storage'; /** * @name LocalStorage * @description * The LocalStorage storage engine uses the browser's local storage system for * storing key/value pairs. * * Note: LocalStorage should ONLY be used for temporary data that you can afford to lose. * Given disk space constraints on a mobile device, local storage might be "cleaned up" * by the operating system (iOS). * * For guaranteed, long-term storage, use the SqlStorage engine which stores data in a file. * * @usage * ```ts * import {Page, Storage, LocalStorage} from 'ionic-angular'; * @Page({ * template: `<ion-content></ion-content>` * }); * export class MyClass{ * constructor(){ * this.local = new Storage(LocalStorage); * this.local.set('didTutorial', 'true'); * } *} *``` * @demo /docs/v2/demos/local-storage/ * @see {@link /docs/v2/platform/storage/ Storage Platform Docs}
* @param {string} key the key you want to lookup in LocalStorage */ get(key: string): Promise<string>; /** * Set a key value pair and save it to LocalStorage * @param {string} key the key you want to save to LocalStorage * @param {string} value the value of the key you're saving */ set(key: string, value: string): Promise<any>; /** * Remove a key from LocalStorage * @param {string} key the key you want to remove from LocalStorage */ remove(key: string): Promise<any>; clear(): Promise<any>; }
*/ export declare class LocalStorage extends StorageEngine { constructor(options?: {}); /** * Get the value of a key in LocalStorage
random_line_split
util.py
import json import os import jinja2 from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), extensions=['jinja2.ext.autoescape'], autoescape=True) def _get_jinja_template(template_filename): return _get_jinja_environment().get_template(template_filename) def send_no_content(request): request.response.headers['Access-Control-Allow-Origin'] = '*' request.response.headers['Content-Type'] = 'application/json' request.response.set_status(204) def send_not_found(request, output_type=message.FORMAT_HTML): request.error(404) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '404 Not found' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def send_server_error(request, output_type=message.FORMAT_HTML): request.error(500) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '500 Internal Server Error' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def
(request, output_type=message.FORMAT_JSON): if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '200 OK' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write('<html> Success! </html>')
send_success
identifier_name
util.py
import json import os import jinja2 from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), extensions=['jinja2.ext.autoescape'], autoescape=True) def _get_jinja_template(template_filename): return _get_jinja_environment().get_template(template_filename) def send_no_content(request): request.response.headers['Access-Control-Allow-Origin'] = '*' request.response.headers['Content-Type'] = 'application/json' request.response.set_status(204) def send_not_found(request, output_type=message.FORMAT_HTML): request.error(404) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '404 Not found' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def send_server_error(request, output_type=message.FORMAT_HTML): request.error(500) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '500 Internal Server Error' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else:
def send_success(request, output_type=message.FORMAT_JSON): if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '200 OK' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write('<html> Success! </html>')
request.response.out.write(_get_jinja_template('not_found.html').render( ))
conditional_block
util.py
from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), extensions=['jinja2.ext.autoescape'], autoescape=True) def _get_jinja_template(template_filename): return _get_jinja_environment().get_template(template_filename) def send_no_content(request): request.response.headers['Access-Control-Allow-Origin'] = '*' request.response.headers['Content-Type'] = 'application/json' request.response.set_status(204) def send_not_found(request, output_type=message.FORMAT_HTML): request.error(404) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '404 Not found' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def send_server_error(request, output_type=message.FORMAT_HTML): request.error(500) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '500 Internal Server Error' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def send_success(request, output_type=message.FORMAT_JSON): if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '200 OK' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write('<html> Success! </html>')
import json import os import jinja2
random_line_split
util.py
import json import os import jinja2 from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), extensions=['jinja2.ext.autoescape'], autoescape=True) def _get_jinja_template(template_filename): return _get_jinja_environment().get_template(template_filename) def send_no_content(request):
def send_not_found(request, output_type=message.FORMAT_HTML): request.error(404) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '404 Not found' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def send_server_error(request, output_type=message.FORMAT_HTML): request.error(500) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '500 Internal Server Error' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write(_get_jinja_template('not_found.html').render( )) def send_success(request, output_type=message.FORMAT_JSON): if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '200 OK' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: request.response.out.write('<html> Success! </html>')
request.response.headers['Access-Control-Allow-Origin'] = '*' request.response.headers['Content-Type'] = 'application/json' request.response.set_status(204)
identifier_body
run.py
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'reward' in data['type'].lower() or 'reward' in data['type'].lower()} row_rules_sheet1_t2 = row_rules_sheet1_t1 col_rules_sheet1_t1 = { '"high"' : lambda data: 'high' in data['amount'], #'return true' : lambda data: True, 'return false' : lambda data: False} col_rules_sheet1_t2 = { 'found "low"' : lambda data: 'low' in data['amount'], 'return true' : lambda data: True, 'return false' : lambda data: False} row_rules_sheet2_t3 = { 'found "fire"': lambda data: 'fire' in data['type'], 'found "Fire"': lambda data: 'Fire' in data['type'], 'found "damage"(ignore letter casing)': lambda data: 'damage' in data['type'].lower()} col_rules_sheet2_t3 = { '"low"' : lambda data: 'low' == data['amount'], '"high"': lambda data: 'high' == data['amount']} def main():
def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__": main()
date = str(datetime.now().date()) print "Maping" excel_template = xlrd.open_workbook("map.xlsx") copyfile('map.xlsx', "map {}.xlsx".format(date)) excel_data = xlrd.open_workbook("data.xlsx") t1_excel_mapper = create_mapper(wb=excel_template,table_index=1,row_rules=row_rules_sheet1_t1,col_rules=col_rules_sheet1_t1) t1_output_data = t1_excel_mapper.run(excel_data) t2_excel_mapper = create_mapper(wb=excel_template,table_index=2,row_rules=row_rules_sheet1_t2,col_rules=col_rules_sheet1_t2) t2_output_data = t2_excel_mapper.run(excel_data) t3_excel_mapper = create_mapper(wb=excel_template,table_index=3,row_rules=row_rules_sheet2_t3,col_rules=col_rules_sheet2_t3) t3_output_data = t3_excel_mapper.run(excel_data) workbook = xlsxwriter.Workbook('output {}.xlsx'.format(date)) worksheet = workbook.add_worksheet() for (row,col),results in t1_output_data.iteritems(): worksheet.write(row, col,len(results)) for (row,col),results in t2_output_data.iteritems(): worksheet.write(row, col,len(results)) worksheet = workbook.add_worksheet() for (row,col),results in t3_output_data.iteritems(): worksheet.write(row, col,len(results)) workbook.close() print "Done."
identifier_body
run.py
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'reward' in data['type'].lower() or 'reward' in data['type'].lower()} row_rules_sheet1_t2 = row_rules_sheet1_t1 col_rules_sheet1_t1 = { '"high"' : lambda data: 'high' in data['amount'], #'return true' : lambda data: True, 'return false' : lambda data: False} col_rules_sheet1_t2 = { 'found "low"' : lambda data: 'low' in data['amount'], 'return true' : lambda data: True, 'return false' : lambda data: False} row_rules_sheet2_t3 = { 'found "fire"': lambda data: 'fire' in data['type'], 'found "Fire"': lambda data: 'Fire' in data['type'], 'found "damage"(ignore letter casing)': lambda data: 'damage' in data['type'].lower()} col_rules_sheet2_t3 = { '"low"' : lambda data: 'low' == data['amount'], '"high"': lambda data: 'high' == data['amount']} def
(): date = str(datetime.now().date()) print "Maping" excel_template = xlrd.open_workbook("map.xlsx") copyfile('map.xlsx', "map {}.xlsx".format(date)) excel_data = xlrd.open_workbook("data.xlsx") t1_excel_mapper = create_mapper(wb=excel_template,table_index=1,row_rules=row_rules_sheet1_t1,col_rules=col_rules_sheet1_t1) t1_output_data = t1_excel_mapper.run(excel_data) t2_excel_mapper = create_mapper(wb=excel_template,table_index=2,row_rules=row_rules_sheet1_t2,col_rules=col_rules_sheet1_t2) t2_output_data = t2_excel_mapper.run(excel_data) t3_excel_mapper = create_mapper(wb=excel_template,table_index=3,row_rules=row_rules_sheet2_t3,col_rules=col_rules_sheet2_t3) t3_output_data = t3_excel_mapper.run(excel_data) workbook = xlsxwriter.Workbook('output {}.xlsx'.format(date)) worksheet = workbook.add_worksheet() for (row,col),results in t1_output_data.iteritems(): worksheet.write(row, col,len(results)) for (row,col),results in t2_output_data.iteritems(): worksheet.write(row, col,len(results)) worksheet = workbook.add_worksheet() for (row,col),results in t3_output_data.iteritems(): worksheet.write(row, col,len(results)) workbook.close() print "Done." def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__": main()
main
identifier_name
run.py
from shutil import copyfile from datetime import datetime
row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'reward' in data['type'].lower() or 'reward' in data['type'].lower()} row_rules_sheet1_t2 = row_rules_sheet1_t1 col_rules_sheet1_t1 = { '"high"' : lambda data: 'high' in data['amount'], #'return true' : lambda data: True, 'return false' : lambda data: False} col_rules_sheet1_t2 = { 'found "low"' : lambda data: 'low' in data['amount'], 'return true' : lambda data: True, 'return false' : lambda data: False} row_rules_sheet2_t3 = { 'found "fire"': lambda data: 'fire' in data['type'], 'found "Fire"': lambda data: 'Fire' in data['type'], 'found "damage"(ignore letter casing)': lambda data: 'damage' in data['type'].lower()} col_rules_sheet2_t3 = { '"low"' : lambda data: 'low' == data['amount'], '"high"': lambda data: 'high' == data['amount']} def main(): date = str(datetime.now().date()) print "Maping" excel_template = xlrd.open_workbook("map.xlsx") copyfile('map.xlsx', "map {}.xlsx".format(date)) excel_data = xlrd.open_workbook("data.xlsx") t1_excel_mapper = create_mapper(wb=excel_template,table_index=1,row_rules=row_rules_sheet1_t1,col_rules=col_rules_sheet1_t1) t1_output_data = t1_excel_mapper.run(excel_data) t2_excel_mapper = create_mapper(wb=excel_template,table_index=2,row_rules=row_rules_sheet1_t2,col_rules=col_rules_sheet1_t2) t2_output_data = t2_excel_mapper.run(excel_data) t3_excel_mapper = create_mapper(wb=excel_template,table_index=3,row_rules=row_rules_sheet2_t3,col_rules=col_rules_sheet2_t3) t3_output_data = t3_excel_mapper.run(excel_data) workbook = xlsxwriter.Workbook('output {}.xlsx'.format(date)) worksheet = workbook.add_worksheet() for (row,col),results in t1_output_data.iteritems(): worksheet.write(row, col,len(results)) for (row,col),results in t2_output_data.iteritems(): worksheet.write(row, col,len(results)) worksheet = workbook.add_worksheet() for (row,col),results in t3_output_data.iteritems(): worksheet.write(row, col,len(results)) workbook.close() print "Done." def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__": main()
from ExcelMapper.mapper import * import xlrd import xlsxwriter
random_line_split
run.py
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'reward' in data['type'].lower() or 'reward' in data['type'].lower()} row_rules_sheet1_t2 = row_rules_sheet1_t1 col_rules_sheet1_t1 = { '"high"' : lambda data: 'high' in data['amount'], #'return true' : lambda data: True, 'return false' : lambda data: False} col_rules_sheet1_t2 = { 'found "low"' : lambda data: 'low' in data['amount'], 'return true' : lambda data: True, 'return false' : lambda data: False} row_rules_sheet2_t3 = { 'found "fire"': lambda data: 'fire' in data['type'], 'found "Fire"': lambda data: 'Fire' in data['type'], 'found "damage"(ignore letter casing)': lambda data: 'damage' in data['type'].lower()} col_rules_sheet2_t3 = { '"low"' : lambda data: 'low' == data['amount'], '"high"': lambda data: 'high' == data['amount']} def main(): date = str(datetime.now().date()) print "Maping" excel_template = xlrd.open_workbook("map.xlsx") copyfile('map.xlsx', "map {}.xlsx".format(date)) excel_data = xlrd.open_workbook("data.xlsx") t1_excel_mapper = create_mapper(wb=excel_template,table_index=1,row_rules=row_rules_sheet1_t1,col_rules=col_rules_sheet1_t1) t1_output_data = t1_excel_mapper.run(excel_data) t2_excel_mapper = create_mapper(wb=excel_template,table_index=2,row_rules=row_rules_sheet1_t2,col_rules=col_rules_sheet1_t2) t2_output_data = t2_excel_mapper.run(excel_data) t3_excel_mapper = create_mapper(wb=excel_template,table_index=3,row_rules=row_rules_sheet2_t3,col_rules=col_rules_sheet2_t3) t3_output_data = t3_excel_mapper.run(excel_data) workbook = xlsxwriter.Workbook('output {}.xlsx'.format(date)) worksheet = workbook.add_worksheet() for (row,col),results in t1_output_data.iteritems(): worksheet.write(row, col,len(results)) for (row,col),results in t2_output_data.iteritems(): worksheet.write(row, col,len(results)) worksheet = workbook.add_worksheet() for (row,col),results in t3_output_data.iteritems():
workbook.close() print "Done." def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__": main()
worksheet.write(row, col,len(results))
conditional_block
setup.py
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-tvdb', version='0.1', packages=['tvdb'], include_package_data=True, license='The MIT License: http://www.opensource.org/licenses/mit-license.php', description='A simple Django app for TV channels DB.', long_description=README, author='Maksym Sokolsky', author_email='misokolsky@gmail.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7',
random_line_split
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): def __init__(self, groupName=None): self.group_groupName = groupName self.group_users = StringList() self.group_auths = StringList() self.euca = EucaAdmin(path=SERVICE_PATH) def __repr__(self): r = 'GROUP \t%s\t' % (self.group_groupName) r = '%s\nUSERS\t%s\t%s' % (r,self.group_groupName,self.group_users) r = '%s\nAUTH\t%s\t%s' % (r,self.group_groupName,self.group_auths) return r def startElement(self, name, attrs, connection): if name == 'euca:users': return self.group_users if name == 'euca:authorizations': return self.group_auths else: return None def endElement(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, value) def get_describe_parser(self):
def cli_describe(self): (options, args) = self.get_describe_parser() self.group_describe(args) def group_describe(self,groups=None): params = {} if groups: self.euca.connection.build_list_params(params,groups,'GroupNames') try: list = self.euca.connection.get_list('DescribeGroups', params, [('euca:item', Group)]) for i in list: print i except EC2ResponseError, ex: self.euca.handle_error(ex) def get_single_parser(self): parser = OptionParser("usage: %prog GROUPNAME",version="Eucalyptus %prog VERSION") (options,args) = parser.parse_args() if len(args) != 1: print "ERROR Required argument GROUPNAME is missing or malformed." parser.print_help() sys.exit(1) else: return (options,args) def cli_add(self): (options, args) = self.get_single_parser() self.group_add(args[0]) def group_add(self, groupName): try: reply = self.euca.connection.get_object('AddGroup', {'GroupName':groupName}, BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex) def cli_delete(self): (options, args) = self.get_single_parser() self.group_delete(args[0]) def group_delete(self, groupName): try: reply = self.euca.connection.get_object('DeleteGroup', {'GroupName':groupName},BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex)
parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION") return parser.parse_args()
random_line_split
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): def __init__(self, groupName=None): self.group_groupName = groupName self.group_users = StringList() self.group_auths = StringList() self.euca = EucaAdmin(path=SERVICE_PATH) def __repr__(self): r = 'GROUP \t%s\t' % (self.group_groupName) r = '%s\nUSERS\t%s\t%s' % (r,self.group_groupName,self.group_users) r = '%s\nAUTH\t%s\t%s' % (r,self.group_groupName,self.group_auths) return r def startElement(self, name, attrs, connection): if name == 'euca:users': return self.group_users if name == 'euca:authorizations':
else: return None def endElement(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, value) def get_describe_parser(self): parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION") return parser.parse_args() def cli_describe(self): (options, args) = self.get_describe_parser() self.group_describe(args) def group_describe(self,groups=None): params = {} if groups: self.euca.connection.build_list_params(params,groups,'GroupNames') try: list = self.euca.connection.get_list('DescribeGroups', params, [('euca:item', Group)]) for i in list: print i except EC2ResponseError, ex: self.euca.handle_error(ex) def get_single_parser(self): parser = OptionParser("usage: %prog GROUPNAME",version="Eucalyptus %prog VERSION") (options,args) = parser.parse_args() if len(args) != 1: print "ERROR Required argument GROUPNAME is missing or malformed." parser.print_help() sys.exit(1) else: return (options,args) def cli_add(self): (options, args) = self.get_single_parser() self.group_add(args[0]) def group_add(self, groupName): try: reply = self.euca.connection.get_object('AddGroup', {'GroupName':groupName}, BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex) def cli_delete(self): (options, args) = self.get_single_parser() self.group_delete(args[0]) def group_delete(self, groupName): try: reply = self.euca.connection.get_object('DeleteGroup', {'GroupName':groupName},BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex)
return self.group_auths
conditional_block
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): def __init__(self, groupName=None): self.group_groupName = groupName self.group_users = StringList() self.group_auths = StringList() self.euca = EucaAdmin(path=SERVICE_PATH) def __repr__(self): r = 'GROUP \t%s\t' % (self.group_groupName) r = '%s\nUSERS\t%s\t%s' % (r,self.group_groupName,self.group_users) r = '%s\nAUTH\t%s\t%s' % (r,self.group_groupName,self.group_auths) return r def startElement(self, name, attrs, connection): if name == 'euca:users': return self.group_users if name == 'euca:authorizations': return self.group_auths else: return None def
(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, value) def get_describe_parser(self): parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION") return parser.parse_args() def cli_describe(self): (options, args) = self.get_describe_parser() self.group_describe(args) def group_describe(self,groups=None): params = {} if groups: self.euca.connection.build_list_params(params,groups,'GroupNames') try: list = self.euca.connection.get_list('DescribeGroups', params, [('euca:item', Group)]) for i in list: print i except EC2ResponseError, ex: self.euca.handle_error(ex) def get_single_parser(self): parser = OptionParser("usage: %prog GROUPNAME",version="Eucalyptus %prog VERSION") (options,args) = parser.parse_args() if len(args) != 1: print "ERROR Required argument GROUPNAME is missing or malformed." parser.print_help() sys.exit(1) else: return (options,args) def cli_add(self): (options, args) = self.get_single_parser() self.group_add(args[0]) def group_add(self, groupName): try: reply = self.euca.connection.get_object('AddGroup', {'GroupName':groupName}, BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex) def cli_delete(self): (options, args) = self.get_single_parser() self.group_delete(args[0]) def group_delete(self, groupName): try: reply = self.euca.connection.get_object('DeleteGroup', {'GroupName':groupName},BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex)
endElement
identifier_name
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): def __init__(self, groupName=None): self.group_groupName = groupName self.group_users = StringList() self.group_auths = StringList() self.euca = EucaAdmin(path=SERVICE_PATH) def __repr__(self): r = 'GROUP \t%s\t' % (self.group_groupName) r = '%s\nUSERS\t%s\t%s' % (r,self.group_groupName,self.group_users) r = '%s\nAUTH\t%s\t%s' % (r,self.group_groupName,self.group_auths) return r def startElement(self, name, attrs, connection): if name == 'euca:users': return self.group_users if name == 'euca:authorizations': return self.group_auths else: return None def endElement(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, value) def get_describe_parser(self): parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION") return parser.parse_args() def cli_describe(self): (options, args) = self.get_describe_parser() self.group_describe(args) def group_describe(self,groups=None): params = {} if groups: self.euca.connection.build_list_params(params,groups,'GroupNames') try: list = self.euca.connection.get_list('DescribeGroups', params, [('euca:item', Group)]) for i in list: print i except EC2ResponseError, ex: self.euca.handle_error(ex) def get_single_parser(self): parser = OptionParser("usage: %prog GROUPNAME",version="Eucalyptus %prog VERSION") (options,args) = parser.parse_args() if len(args) != 1: print "ERROR Required argument GROUPNAME is missing or malformed." parser.print_help() sys.exit(1) else: return (options,args) def cli_add(self): (options, args) = self.get_single_parser() self.group_add(args[0]) def group_add(self, groupName):
def cli_delete(self): (options, args) = self.get_single_parser() self.group_delete(args[0]) def group_delete(self, groupName): try: reply = self.euca.connection.get_object('DeleteGroup', {'GroupName':groupName},BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex)
try: reply = self.euca.connection.get_object('AddGroup', {'GroupName':groupName}, BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex)
identifier_body
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = require('cheerio-tableparser') function recognize_page_type(page_parsed) { // console.error("TYPE: " + typeof(page_parsed)) // DEBUG: // console.error("TITLE IS " + pageParsed('head title').text()) // If title is "PublicViewStatus"; is OK; otherwise ERROR out!! if (page_parsed('head title').text() == "PublicViewStatus") { // Aduan Information // id="dlAduan" // DEBUG: // console.error("ADUAN: " + pageParsed('#Table9')) /* console.error("====== ADUAN_DATA: =====\n" + util.inspect( pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ))) */ /* NO NEED TRANSPOSE!! :P const aduanData = pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) */ const aduan_data = page_parsed('#Table9').parsetable(false, false, true) // DEBUG: /* console.error("SIZE: " + aduan_data.length) aduanData[0].every((element, index, array) => { console.error("EL: " + util.inspect(element) + " ID: " + index ) }) */ // Choose the column number; then we can get out the key/value // aduanData[0] for the label // aduanData[1] for the value // DEBUG: /* aduan_data[1].forEach((element, index) => { console.error('a[' + index + '] = ' + element) }) */ // console.error("ADUANID: " + aduan_data[1][0]) // Tindakan Table // id="dsTindakan" // DEBUG: // console.error("TINDAKAN: " + pageParsed('#dsTindakan')) // References: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array // Transpose assumes matrix (same size both end); not suitable // const transpose = a => a.map((_, c) => a.map(r => r[c])) // Last solution by @tatomyr works!! const tindakan_data = page_parsed('#dsTindakan').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) // DEBUG: /* console.error("TINDAKAN_DATA:" + util.inspect(tindakan_data)) console.error("TINDAKAN_LENGTH: " + tindakan_data.length) */ if (tindakan_data.length == 1)
else { return { "page_type": "good", "aduan_id": aduan_data[1][0] } } } else { return { "page_type": "error" } } // Should not get here .. is bad! return { "page_type": "unknown" } } function extract_table(loaded_raw_content) { if (loaded_raw_content === null || loaded_raw_content === undefined) { return { "error": FATAL_CONTENT } } const page_parsed = cheerio.load(loaded_raw_content) // Setup cheerio-tableparser tableParser(page_parsed) // Extract out page type and other goodies? const res = recognize_page_type(page_parsed) if (res.page_type == "error") { // Assumes Error Page; but it is loaded correctly .. return { "error": null, "type": "error" } } else if (res.page_type == "unknown") { return { "error": FATAL_UNKNOWN, "type": "error" } } // Type: "good" or "empty" return { "error": null, "type": res.page_type, "aduan_id": res.aduan_id } } module.exports = { execute: extract_table }
{ return { "page_type": "empty", "aduan_id": aduan_data[1][0] } }
conditional_block
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = require('cheerio-tableparser') function
(page_parsed) { // console.error("TYPE: " + typeof(page_parsed)) // DEBUG: // console.error("TITLE IS " + pageParsed('head title').text()) // If title is "PublicViewStatus"; is OK; otherwise ERROR out!! if (page_parsed('head title').text() == "PublicViewStatus") { // Aduan Information // id="dlAduan" // DEBUG: // console.error("ADUAN: " + pageParsed('#Table9')) /* console.error("====== ADUAN_DATA: =====\n" + util.inspect( pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ))) */ /* NO NEED TRANSPOSE!! :P const aduanData = pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) */ const aduan_data = page_parsed('#Table9').parsetable(false, false, true) // DEBUG: /* console.error("SIZE: " + aduan_data.length) aduanData[0].every((element, index, array) => { console.error("EL: " + util.inspect(element) + " ID: " + index ) }) */ // Choose the column number; then we can get out the key/value // aduanData[0] for the label // aduanData[1] for the value // DEBUG: /* aduan_data[1].forEach((element, index) => { console.error('a[' + index + '] = ' + element) }) */ // console.error("ADUANID: " + aduan_data[1][0]) // Tindakan Table // id="dsTindakan" // DEBUG: // console.error("TINDAKAN: " + pageParsed('#dsTindakan')) // References: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array // Transpose assumes matrix (same size both end); not suitable // const transpose = a => a.map((_, c) => a.map(r => r[c])) // Last solution by @tatomyr works!! const tindakan_data = page_parsed('#dsTindakan').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) // DEBUG: /* console.error("TINDAKAN_DATA:" + util.inspect(tindakan_data)) console.error("TINDAKAN_LENGTH: " + tindakan_data.length) */ if (tindakan_data.length == 1) { return { "page_type": "empty", "aduan_id": aduan_data[1][0] } } else { return { "page_type": "good", "aduan_id": aduan_data[1][0] } } } else { return { "page_type": "error" } } // Should not get here .. is bad! return { "page_type": "unknown" } } function extract_table(loaded_raw_content) { if (loaded_raw_content === null || loaded_raw_content === undefined) { return { "error": FATAL_CONTENT } } const page_parsed = cheerio.load(loaded_raw_content) // Setup cheerio-tableparser tableParser(page_parsed) // Extract out page type and other goodies? const res = recognize_page_type(page_parsed) if (res.page_type == "error") { // Assumes Error Page; but it is loaded correctly .. return { "error": null, "type": "error" } } else if (res.page_type == "unknown") { return { "error": FATAL_UNKNOWN, "type": "error" } } // Type: "good" or "empty" return { "error": null, "type": res.page_type, "aduan_id": res.aduan_id } } module.exports = { execute: extract_table }
recognize_page_type
identifier_name
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = require('cheerio-tableparser') function recognize_page_type(page_parsed)
function extract_table(loaded_raw_content) { if (loaded_raw_content === null || loaded_raw_content === undefined) { return { "error": FATAL_CONTENT } } const page_parsed = cheerio.load(loaded_raw_content) // Setup cheerio-tableparser tableParser(page_parsed) // Extract out page type and other goodies? const res = recognize_page_type(page_parsed) if (res.page_type == "error") { // Assumes Error Page; but it is loaded correctly .. return { "error": null, "type": "error" } } else if (res.page_type == "unknown") { return { "error": FATAL_UNKNOWN, "type": "error" } } // Type: "good" or "empty" return { "error": null, "type": res.page_type, "aduan_id": res.aduan_id } } module.exports = { execute: extract_table }
{ // console.error("TYPE: " + typeof(page_parsed)) // DEBUG: // console.error("TITLE IS " + pageParsed('head title').text()) // If title is "PublicViewStatus"; is OK; otherwise ERROR out!! if (page_parsed('head title').text() == "PublicViewStatus") { // Aduan Information // id="dlAduan" // DEBUG: // console.error("ADUAN: " + pageParsed('#Table9')) /* console.error("====== ADUAN_DATA: =====\n" + util.inspect( pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ))) */ /* NO NEED TRANSPOSE!! :P const aduanData = pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) */ const aduan_data = page_parsed('#Table9').parsetable(false, false, true) // DEBUG: /* console.error("SIZE: " + aduan_data.length) aduanData[0].every((element, index, array) => { console.error("EL: " + util.inspect(element) + " ID: " + index ) }) */ // Choose the column number; then we can get out the key/value // aduanData[0] for the label // aduanData[1] for the value // DEBUG: /* aduan_data[1].forEach((element, index) => { console.error('a[' + index + '] = ' + element) }) */ // console.error("ADUANID: " + aduan_data[1][0]) // Tindakan Table // id="dsTindakan" // DEBUG: // console.error("TINDAKAN: " + pageParsed('#dsTindakan')) // References: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array // Transpose assumes matrix (same size both end); not suitable // const transpose = a => a.map((_, c) => a.map(r => r[c])) // Last solution by @tatomyr works!! const tindakan_data = page_parsed('#dsTindakan').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) // DEBUG: /* console.error("TINDAKAN_DATA:" + util.inspect(tindakan_data)) console.error("TINDAKAN_LENGTH: " + tindakan_data.length) */ if (tindakan_data.length == 1) { return { "page_type": "empty", "aduan_id": aduan_data[1][0] } } else { return { "page_type": "good", "aduan_id": aduan_data[1][0] } } } else { return { "page_type": "error" } } // Should not get here .. is bad! return { "page_type": "unknown" } }
identifier_body
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = require('cheerio-tableparser') function recognize_page_type(page_parsed) { // console.error("TYPE: " + typeof(page_parsed)) // DEBUG: // console.error("TITLE IS " + pageParsed('head title').text()) // If title is "PublicViewStatus"; is OK; otherwise ERROR out!! if (page_parsed('head title').text() == "PublicViewStatus") { // Aduan Information // id="dlAduan" // DEBUG: // console.error("ADUAN: " + pageParsed('#Table9')) /* console.error("====== ADUAN_DATA: =====\n" + util.inspect( pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ))) */ /* NO NEED TRANSPOSE!! :P const aduanData = pageParsed('#Table9').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) */ const aduan_data = page_parsed('#Table9').parsetable(false, false, true) // DEBUG: /* console.error("SIZE: " + aduan_data.length) aduanData[0].every((element, index, array) => { console.error("EL: " + util.inspect(element) + " ID: " + index ) }) */ // Choose the column number; then we can get out the key/value // aduanData[0] for the label // aduanData[1] for the value // DEBUG: /* aduan_data[1].forEach((element, index) => { console.error('a[' + index + '] = ' + element) }) */ // console.error("ADUANID: " + aduan_data[1][0]) // Tindakan Table // id="dsTindakan" // DEBUG: // console.error("TINDAKAN: " + pageParsed('#dsTindakan')) // References: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array // Transpose assumes matrix (same size both end); not suitable // const transpose = a => a.map((_, c) => a.map(r => r[c])) // Last solution by @tatomyr works!! const tindakan_data = page_parsed('#dsTindakan').parsetable(false, false, true).reduce( (p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), [] ) // DEBUG: /* console.error("TINDAKAN_DATA:" + util.inspect(tindakan_data)) console.error("TINDAKAN_LENGTH: " + tindakan_data.length) */ if (tindakan_data.length == 1) { return { "page_type": "empty", "aduan_id": aduan_data[1][0] } } else { return { "page_type": "good", "aduan_id": aduan_data[1][0] } } } else { return { "page_type": "error" } } // Should not get here .. is bad! return { "page_type": "unknown" } } function extract_table(loaded_raw_content) { if (loaded_raw_content === null || loaded_raw_content === undefined) { return { "error": FATAL_CONTENT }
} const page_parsed = cheerio.load(loaded_raw_content) // Setup cheerio-tableparser tableParser(page_parsed) // Extract out page type and other goodies? const res = recognize_page_type(page_parsed) if (res.page_type == "error") { // Assumes Error Page; but it is loaded correctly .. return { "error": null, "type": "error" } } else if (res.page_type == "unknown") { return { "error": FATAL_UNKNOWN, "type": "error" } } // Type: "good" or "empty" return { "error": null, "type": res.page_type, "aduan_id": res.aduan_id } } module.exports = { execute: extract_table }
random_line_split
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: csComp.Services.Feed[] = []; public layer: csComp.Services.ProjectLayer; public featureTypes: { [key: string]: csComp.Services.IFeatureType } = {}; public kanban: KanbanColumn.KanbanConfig; // $inject annotation. // It provides $injector with information about dependencies to be injected into constructor // it is better to have it close to the constructor, because the parameters must match in count and type. // See http://docs.angularjs.org/guide/di public static $inject = [ '$scope', 'layerService', 'messageBusService' ]; public addFeature(key: string) { var f = new csComp.Services.Feature(); f.properties = {}; var ft = this.featureTypes[key]; if (ft.properties) { for (var k in ft.properties) { f.properties[k] = JSON.parse(JSON.stringify(ft.properties[k])); } } f.properties["date"] = new Date(); f.properties["updated"] = new Date(); f.properties["featureTypeId"] = key; if (!f.properties.hasOwnProperty('Name')) f.properties['Name'] = ft.name; this.layer.data.features.push(f); this.$layerService.initFeature(f, this.layer); this.$layerService.editFeature(f); } // dependencies are injected via AngularJS $injector // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html constructor( private $scope: IKanbanBoardScope, private $layerService: csComp.Services.LayerService, private $messageBus: csComp.Services.MessageBusService ) { $scope.vm = this; var par = <any>$scope.$parent; this.kanban = par.widget.data; this.$messageBus.subscribe("typesource", (s: string) => { this.initLayer(); }); this.initLayer(); } private
() { console.log('kanban:loaded project'); var layerId = this.kanban.columns[0].filters.layerIds[0]; this.layer = this.$layerService.findLayer(layerId); if (this.layer) { if (this.layer.typeUrl && this.$layerService.typesResources.hasOwnProperty(this.layer.typeUrl)) { if (this.kanban.featureTypesToAdd) { this.featureTypes = {}; for (var ft in this.$layerService.typesResources[this.layer.typeUrl].featureTypes) { if (this.kanban.featureTypesToAdd.indexOf(ft) > -1) this.featureTypes[ft] = this.$layerService.typesResources[this.layer.typeUrl].featureTypes[ft]; } } else { this.featureTypes = this.$layerService.typesResources[this.layer.typeUrl].featureTypes; } console.log('feature types'); console.log(this.featureTypes); } } } } }
initLayer
identifier_name
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: csComp.Services.Feed[] = []; public layer: csComp.Services.ProjectLayer; public featureTypes: { [key: string]: csComp.Services.IFeatureType } = {}; public kanban: KanbanColumn.KanbanConfig; // $inject annotation. // It provides $injector with information about dependencies to be injected into constructor // it is better to have it close to the constructor, because the parameters must match in count and type. // See http://docs.angularjs.org/guide/di public static $inject = [ '$scope', 'layerService', 'messageBusService' ]; public addFeature(key: string) { var f = new csComp.Services.Feature(); f.properties = {}; var ft = this.featureTypes[key]; if (ft.properties) { for (var k in ft.properties) { f.properties[k] = JSON.parse(JSON.stringify(ft.properties[k])); } } f.properties["date"] = new Date(); f.properties["updated"] = new Date(); f.properties["featureTypeId"] = key; if (!f.properties.hasOwnProperty('Name')) f.properties['Name'] = ft.name; this.layer.data.features.push(f); this.$layerService.initFeature(f, this.layer); this.$layerService.editFeature(f); } // dependencies are injected via AngularJS $injector // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html constructor( private $scope: IKanbanBoardScope, private $layerService: csComp.Services.LayerService, private $messageBus: csComp.Services.MessageBusService ) { $scope.vm = this; var par = <any>$scope.$parent; this.kanban = par.widget.data; this.$messageBus.subscribe("typesource", (s: string) => { this.initLayer(); }); this.initLayer(); } private initLayer() { console.log('kanban:loaded project'); var layerId = this.kanban.columns[0].filters.layerIds[0]; this.layer = this.$layerService.findLayer(layerId); if (this.layer) { if (this.layer.typeUrl && this.$layerService.typesResources.hasOwnProperty(this.layer.typeUrl)) { if (this.kanban.featureTypesToAdd) { this.featureTypes = {}; for (var ft in this.$layerService.typesResources[this.layer.typeUrl].featureTypes) { if (this.kanban.featureTypesToAdd.indexOf(ft) > -1) this.featureTypes[ft] = this.$layerService.typesResources[this.layer.typeUrl].featureTypes[ft]; } } else
console.log('feature types'); console.log(this.featureTypes); } } } } }
{ this.featureTypes = this.$layerService.typesResources[this.layer.typeUrl].featureTypes; }
conditional_block
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: csComp.Services.Feed[] = []; public layer: csComp.Services.ProjectLayer; public featureTypes: { [key: string]: csComp.Services.IFeatureType } = {}; public kanban: KanbanColumn.KanbanConfig; // $inject annotation. // It provides $injector with information about dependencies to be injected into constructor // it is better to have it close to the constructor, because the parameters must match in count and type. // See http://docs.angularjs.org/guide/di public static $inject = [ '$scope', 'layerService', 'messageBusService' ]; public addFeature(key: string) { var f = new csComp.Services.Feature(); f.properties = {}; var ft = this.featureTypes[key]; if (ft.properties) { for (var k in ft.properties) { f.properties[k] = JSON.parse(JSON.stringify(ft.properties[k])); } } f.properties["date"] = new Date(); f.properties["updated"] = new Date(); f.properties["featureTypeId"] = key; if (!f.properties.hasOwnProperty('Name')) f.properties['Name'] = ft.name; this.layer.data.features.push(f); this.$layerService.initFeature(f, this.layer); this.$layerService.editFeature(f); } // dependencies are injected via AngularJS $injector // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html constructor( private $scope: IKanbanBoardScope, private $layerService: csComp.Services.LayerService, private $messageBus: csComp.Services.MessageBusService )
private initLayer() { console.log('kanban:loaded project'); var layerId = this.kanban.columns[0].filters.layerIds[0]; this.layer = this.$layerService.findLayer(layerId); if (this.layer) { if (this.layer.typeUrl && this.$layerService.typesResources.hasOwnProperty(this.layer.typeUrl)) { if (this.kanban.featureTypesToAdd) { this.featureTypes = {}; for (var ft in this.$layerService.typesResources[this.layer.typeUrl].featureTypes) { if (this.kanban.featureTypesToAdd.indexOf(ft) > -1) this.featureTypes[ft] = this.$layerService.typesResources[this.layer.typeUrl].featureTypes[ft]; } } else { this.featureTypes = this.$layerService.typesResources[this.layer.typeUrl].featureTypes; } console.log('feature types'); console.log(this.featureTypes); } } } } }
{ $scope.vm = this; var par = <any>$scope.$parent; this.kanban = par.widget.data; this.$messageBus.subscribe("typesource", (s: string) => { this.initLayer(); }); this.initLayer(); }
identifier_body
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: csComp.Services.Feed[] = []; public layer: csComp.Services.ProjectLayer; public featureTypes: { [key: string]: csComp.Services.IFeatureType } = {}; public kanban: KanbanColumn.KanbanConfig; // $inject annotation. // It provides $injector with information about dependencies to be injected into constructor // it is better to have it close to the constructor, because the parameters must match in count and type. // See http://docs.angularjs.org/guide/di public static $inject = [ '$scope', 'layerService', 'messageBusService' ]; public addFeature(key: string) { var f = new csComp.Services.Feature(); f.properties = {}; var ft = this.featureTypes[key]; if (ft.properties) { for (var k in ft.properties) { f.properties[k] = JSON.parse(JSON.stringify(ft.properties[k])); } } f.properties["date"] = new Date(); f.properties["updated"] = new Date(); f.properties["featureTypeId"] = key; if (!f.properties.hasOwnProperty('Name')) f.properties['Name'] = ft.name; this.layer.data.features.push(f); this.$layerService.initFeature(f, this.layer); this.$layerService.editFeature(f); } // dependencies are injected via AngularJS $injector // controller's name is registered in Application.ts and specified from ng-controller attribute in index.html constructor( private $scope: IKanbanBoardScope, private $layerService: csComp.Services.LayerService, private $messageBus: csComp.Services.MessageBusService ) { $scope.vm = this; var par = <any>$scope.$parent; this.kanban = par.widget.data; this.$messageBus.subscribe("typesource", (s: string) => { this.initLayer(); }); this.initLayer(); } private initLayer() { console.log('kanban:loaded project'); var layerId = this.kanban.columns[0].filters.layerIds[0]; this.layer = this.$layerService.findLayer(layerId); if (this.layer) { if (this.layer.typeUrl && this.$layerService.typesResources.hasOwnProperty(this.layer.typeUrl)) { if (this.kanban.featureTypesToAdd) { this.featureTypes = {}; for (var ft in this.$layerService.typesResources[this.layer.typeUrl].featureTypes) { if (this.kanban.featureTypesToAdd.indexOf(ft) > -1) this.featureTypes[ft] = this.$layerService.typesResources[this.layer.typeUrl].featureTypes[ft]; } } else { this.featureTypes = this.$layerService.typesResources[this.layer.typeUrl].featureTypes; } console.log('feature types');
} } } } }
console.log(this.featureTypes);
random_line_split
index.ts
import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatCardModule} from '@angular/material/card'; import {MatCheckboxModule} from '@angular/material/checkbox'; import {MatRadioModule} from '@angular/material/radio'; import {CheckboxConfigurableExample} from './checkbox-configurable/checkbox-configurable-example'; import {CheckboxHarnessExample} from './checkbox-harness/checkbox-harness-example'; import {CheckboxOverviewExample} from './checkbox-overview/checkbox-overview-example'; import {CheckboxReactiveFormsExample} from './checkbox-reactive-forms/checkbox-reactive-forms-example'; export { CheckboxConfigurableExample, CheckboxOverviewExample, CheckboxHarnessExample, CheckboxReactiveFormsExample, };
CheckboxReactiveFormsExample, ]; @NgModule({ imports: [ CommonModule, MatCardModule, MatCheckboxModule, MatRadioModule, FormsModule, ReactiveFormsModule, ], declarations: EXAMPLES, exports: EXAMPLES, }) export class CheckboxExamplesModule {}
const EXAMPLES = [ CheckboxConfigurableExample, CheckboxOverviewExample, CheckboxHarnessExample,
random_line_split
index.ts
import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatCardModule} from '@angular/material/card'; import {MatCheckboxModule} from '@angular/material/checkbox'; import {MatRadioModule} from '@angular/material/radio'; import {CheckboxConfigurableExample} from './checkbox-configurable/checkbox-configurable-example'; import {CheckboxHarnessExample} from './checkbox-harness/checkbox-harness-example'; import {CheckboxOverviewExample} from './checkbox-overview/checkbox-overview-example'; import {CheckboxReactiveFormsExample} from './checkbox-reactive-forms/checkbox-reactive-forms-example'; export { CheckboxConfigurableExample, CheckboxOverviewExample, CheckboxHarnessExample, CheckboxReactiveFormsExample, }; const EXAMPLES = [ CheckboxConfigurableExample, CheckboxOverviewExample, CheckboxHarnessExample, CheckboxReactiveFormsExample, ]; @NgModule({ imports: [ CommonModule, MatCardModule, MatCheckboxModule, MatRadioModule, FormsModule, ReactiveFormsModule, ], declarations: EXAMPLES, exports: EXAMPLES, }) export class
{}
CheckboxExamplesModule
identifier_name
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function Store(name, minCust, maxCust, avgCookieSale) { this.name = name; this.minCust = minCust; this.maxCust = maxCust; this.avgCookieSale = avgCookieSale; this.hourlySales = []; this.hourlyCust = []; this.totalSales = 0; this.calcSalesByHour(); allStores.push(this); }; Store.prototype.calcCustPerHour = function () { for(var i = 0; i < timesOfDay.length; i++){ var cust = Math.floor(Math.random() * (this.maxCust - this.minCust) + this.minCust); this.hourlyCust.push(cust); } }; Store.prototype.calcSalesByHour = function(){ this.calcCustPerHour(); for(var i = 0; i < timesOfDay.length; i++){ var cookies = Math.ceil(this.hourlyCust[i] * this.avgCookieSale); this.hourlySales.push(cookies); this.totalSales += cookies; } return this.hourlySales; }; Store.prototype.render = function(){ var trEl = document.createElement('tr'); var tdEl = document.createElement('td'); tdEl.textContent = this.name; trEl.appendChild(tdEl); for(var i = 0; i < timesOfDay.length; i++) { tdEl = document.createElement('td'); tdEl.textContent = this.hourlySales[i]; trEl.appendChild(tdEl); } tdEl = document.createElement('td'); tdEl.textContent = this.totalSales; trEl.appendChild(tdEl); myTable.appendChild(trEl); }; function makeHeader() { var thEl = document.createElement('th'); var trEl = document.createElement('tr'); thEl.textContent = 'Location'; trEl.appendChild(thEl); for(var i = 0; i < timesOfDay.length; i++){ var thEl = document.createElement('th'); // console.log('hello'); thEl.textContent = timesOfDay[i]; trEl.appendChild(thEl); } thEl = document.createElement('th'); thEl.textContent = 'Grand Total'; trEl.appendChild(thEl); myTable.appendChild(trEl); } function renderAllLocations(){ for(var i = 0; i < allStores.length; i++){ allStores[i].render(); } } function makeFooter() { removeFooter(); var tfootEl = document.createElement('tfoot'); tfootEl.id = 'tableFooter'; var trEl = document.createElement('tr'); trEl.textContent = 'Hourly Totals'; var dailyTotalAllLocations = 0; for(var i = 0; i < timesOfDay.length; i++){ var total = 0; for(var j = 0; j < allStores.length; j++){ total += allStores[j].hourlySales[i]; } var tdEl = document.createElement('td'); tdEl.textContent = total; trEl.appendChild(tdEl); dailyTotalAllLocations += total; // trEl.appendChild(thEl); } tdEl = document.createElement('td'); tdEl.textContent = dailyTotalAllLocations; trEl.appendChild(tdEl); tfootEl.appendChild(trEl); myTable.appendChild(tfootEl); } function removeFooter()
//event listener function makeStore(event){ event.preventDefault(); myTable.innerHtml = ''; var name = event.target.name.value; var minCust = parseInt(event.target.minCust.value); var maxCust = parseInt(event.target.maxCust.value); var avgCookieSale = parseFloat(event.target.avgCookieSale.value); var addStore = new Store(name, minCust, maxCust, avgCookieSale); event.target.name.value = null; event.target.minCust.value = null; event.target.maxCust.value = null; event.target.avgCookieSale.value = null; addStore.render(); makeFooter(); console.log('first calls'); } //Variables ready to make the individual store objects var pikePlace = new Store('Pikes Market', 23, 65, 6.3); var seaTac = new Store ('Seatac', 3, 24, 1.2); var seaCent = new Store('Seattle Center', 11, 38, 3.7); var capHill = new Store('Capitol Hill', 30, 28, 2.3); var alki = new Store('Alki', 2, 16, 4.6); makeHeader(); renderAllLocations(); makeFooter(); console.log('last calls'); form.addEventListener('submit', makeStore);
{ var footerRef = document.getElementById('tableFooter'); if (footerRef !== null){ footerRef.parentElement.removeChild(footerRef); } }
identifier_body
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function
(name, minCust, maxCust, avgCookieSale) { this.name = name; this.minCust = minCust; this.maxCust = maxCust; this.avgCookieSale = avgCookieSale; this.hourlySales = []; this.hourlyCust = []; this.totalSales = 0; this.calcSalesByHour(); allStores.push(this); }; Store.prototype.calcCustPerHour = function () { for(var i = 0; i < timesOfDay.length; i++){ var cust = Math.floor(Math.random() * (this.maxCust - this.minCust) + this.minCust); this.hourlyCust.push(cust); } }; Store.prototype.calcSalesByHour = function(){ this.calcCustPerHour(); for(var i = 0; i < timesOfDay.length; i++){ var cookies = Math.ceil(this.hourlyCust[i] * this.avgCookieSale); this.hourlySales.push(cookies); this.totalSales += cookies; } return this.hourlySales; }; Store.prototype.render = function(){ var trEl = document.createElement('tr'); var tdEl = document.createElement('td'); tdEl.textContent = this.name; trEl.appendChild(tdEl); for(var i = 0; i < timesOfDay.length; i++) { tdEl = document.createElement('td'); tdEl.textContent = this.hourlySales[i]; trEl.appendChild(tdEl); } tdEl = document.createElement('td'); tdEl.textContent = this.totalSales; trEl.appendChild(tdEl); myTable.appendChild(trEl); }; function makeHeader() { var thEl = document.createElement('th'); var trEl = document.createElement('tr'); thEl.textContent = 'Location'; trEl.appendChild(thEl); for(var i = 0; i < timesOfDay.length; i++){ var thEl = document.createElement('th'); // console.log('hello'); thEl.textContent = timesOfDay[i]; trEl.appendChild(thEl); } thEl = document.createElement('th'); thEl.textContent = 'Grand Total'; trEl.appendChild(thEl); myTable.appendChild(trEl); } function renderAllLocations(){ for(var i = 0; i < allStores.length; i++){ allStores[i].render(); } } function makeFooter() { removeFooter(); var tfootEl = document.createElement('tfoot'); tfootEl.id = 'tableFooter'; var trEl = document.createElement('tr'); trEl.textContent = 'Hourly Totals'; var dailyTotalAllLocations = 0; for(var i = 0; i < timesOfDay.length; i++){ var total = 0; for(var j = 0; j < allStores.length; j++){ total += allStores[j].hourlySales[i]; } var tdEl = document.createElement('td'); tdEl.textContent = total; trEl.appendChild(tdEl); dailyTotalAllLocations += total; // trEl.appendChild(thEl); } tdEl = document.createElement('td'); tdEl.textContent = dailyTotalAllLocations; trEl.appendChild(tdEl); tfootEl.appendChild(trEl); myTable.appendChild(tfootEl); } function removeFooter(){ var footerRef = document.getElementById('tableFooter'); if (footerRef !== null){ footerRef.parentElement.removeChild(footerRef); } } //event listener function makeStore(event){ event.preventDefault(); myTable.innerHtml = ''; var name = event.target.name.value; var minCust = parseInt(event.target.minCust.value); var maxCust = parseInt(event.target.maxCust.value); var avgCookieSale = parseFloat(event.target.avgCookieSale.value); var addStore = new Store(name, minCust, maxCust, avgCookieSale); event.target.name.value = null; event.target.minCust.value = null; event.target.maxCust.value = null; event.target.avgCookieSale.value = null; addStore.render(); makeFooter(); console.log('first calls'); } //Variables ready to make the individual store objects var pikePlace = new Store('Pikes Market', 23, 65, 6.3); var seaTac = new Store ('Seatac', 3, 24, 1.2); var seaCent = new Store('Seattle Center', 11, 38, 3.7); var capHill = new Store('Capitol Hill', 30, 28, 2.3); var alki = new Store('Alki', 2, 16, 4.6); makeHeader(); renderAllLocations(); makeFooter(); console.log('last calls'); form.addEventListener('submit', makeStore);
Store
identifier_name
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function Store(name, minCust, maxCust, avgCookieSale) { this.name = name; this.minCust = minCust; this.maxCust = maxCust; this.avgCookieSale = avgCookieSale; this.hourlySales = []; this.hourlyCust = []; this.totalSales = 0; this.calcSalesByHour(); allStores.push(this); }; Store.prototype.calcCustPerHour = function () { for(var i = 0; i < timesOfDay.length; i++){ var cust = Math.floor(Math.random() * (this.maxCust - this.minCust) + this.minCust); this.hourlyCust.push(cust); } }; Store.prototype.calcSalesByHour = function(){ this.calcCustPerHour(); for(var i = 0; i < timesOfDay.length; i++){ var cookies = Math.ceil(this.hourlyCust[i] * this.avgCookieSale); this.hourlySales.push(cookies); this.totalSales += cookies; } return this.hourlySales; }; Store.prototype.render = function(){ var trEl = document.createElement('tr'); var tdEl = document.createElement('td'); tdEl.textContent = this.name; trEl.appendChild(tdEl); for(var i = 0; i < timesOfDay.length; i++) { tdEl = document.createElement('td'); tdEl.textContent = this.hourlySales[i]; trEl.appendChild(tdEl); } tdEl = document.createElement('td'); tdEl.textContent = this.totalSales;
function makeHeader() { var thEl = document.createElement('th'); var trEl = document.createElement('tr'); thEl.textContent = 'Location'; trEl.appendChild(thEl); for(var i = 0; i < timesOfDay.length; i++){ var thEl = document.createElement('th'); // console.log('hello'); thEl.textContent = timesOfDay[i]; trEl.appendChild(thEl); } thEl = document.createElement('th'); thEl.textContent = 'Grand Total'; trEl.appendChild(thEl); myTable.appendChild(trEl); } function renderAllLocations(){ for(var i = 0; i < allStores.length; i++){ allStores[i].render(); } } function makeFooter() { removeFooter(); var tfootEl = document.createElement('tfoot'); tfootEl.id = 'tableFooter'; var trEl = document.createElement('tr'); trEl.textContent = 'Hourly Totals'; var dailyTotalAllLocations = 0; for(var i = 0; i < timesOfDay.length; i++){ var total = 0; for(var j = 0; j < allStores.length; j++){ total += allStores[j].hourlySales[i]; } var tdEl = document.createElement('td'); tdEl.textContent = total; trEl.appendChild(tdEl); dailyTotalAllLocations += total; // trEl.appendChild(thEl); } tdEl = document.createElement('td'); tdEl.textContent = dailyTotalAllLocations; trEl.appendChild(tdEl); tfootEl.appendChild(trEl); myTable.appendChild(tfootEl); } function removeFooter(){ var footerRef = document.getElementById('tableFooter'); if (footerRef !== null){ footerRef.parentElement.removeChild(footerRef); } } //event listener function makeStore(event){ event.preventDefault(); myTable.innerHtml = ''; var name = event.target.name.value; var minCust = parseInt(event.target.minCust.value); var maxCust = parseInt(event.target.maxCust.value); var avgCookieSale = parseFloat(event.target.avgCookieSale.value); var addStore = new Store(name, minCust, maxCust, avgCookieSale); event.target.name.value = null; event.target.minCust.value = null; event.target.maxCust.value = null; event.target.avgCookieSale.value = null; addStore.render(); makeFooter(); console.log('first calls'); } //Variables ready to make the individual store objects var pikePlace = new Store('Pikes Market', 23, 65, 6.3); var seaTac = new Store ('Seatac', 3, 24, 1.2); var seaCent = new Store('Seattle Center', 11, 38, 3.7); var capHill = new Store('Capitol Hill', 30, 28, 2.3); var alki = new Store('Alki', 2, 16, 4.6); makeHeader(); renderAllLocations(); makeFooter(); console.log('last calls'); form.addEventListener('submit', makeStore);
trEl.appendChild(tdEl); myTable.appendChild(trEl); };
random_line_split
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function Store(name, minCust, maxCust, avgCookieSale) { this.name = name; this.minCust = minCust; this.maxCust = maxCust; this.avgCookieSale = avgCookieSale; this.hourlySales = []; this.hourlyCust = []; this.totalSales = 0; this.calcSalesByHour(); allStores.push(this); }; Store.prototype.calcCustPerHour = function () { for(var i = 0; i < timesOfDay.length; i++)
}; Store.prototype.calcSalesByHour = function(){ this.calcCustPerHour(); for(var i = 0; i < timesOfDay.length; i++){ var cookies = Math.ceil(this.hourlyCust[i] * this.avgCookieSale); this.hourlySales.push(cookies); this.totalSales += cookies; } return this.hourlySales; }; Store.prototype.render = function(){ var trEl = document.createElement('tr'); var tdEl = document.createElement('td'); tdEl.textContent = this.name; trEl.appendChild(tdEl); for(var i = 0; i < timesOfDay.length; i++) { tdEl = document.createElement('td'); tdEl.textContent = this.hourlySales[i]; trEl.appendChild(tdEl); } tdEl = document.createElement('td'); tdEl.textContent = this.totalSales; trEl.appendChild(tdEl); myTable.appendChild(trEl); }; function makeHeader() { var thEl = document.createElement('th'); var trEl = document.createElement('tr'); thEl.textContent = 'Location'; trEl.appendChild(thEl); for(var i = 0; i < timesOfDay.length; i++){ var thEl = document.createElement('th'); // console.log('hello'); thEl.textContent = timesOfDay[i]; trEl.appendChild(thEl); } thEl = document.createElement('th'); thEl.textContent = 'Grand Total'; trEl.appendChild(thEl); myTable.appendChild(trEl); } function renderAllLocations(){ for(var i = 0; i < allStores.length; i++){ allStores[i].render(); } } function makeFooter() { removeFooter(); var tfootEl = document.createElement('tfoot'); tfootEl.id = 'tableFooter'; var trEl = document.createElement('tr'); trEl.textContent = 'Hourly Totals'; var dailyTotalAllLocations = 0; for(var i = 0; i < timesOfDay.length; i++){ var total = 0; for(var j = 0; j < allStores.length; j++){ total += allStores[j].hourlySales[i]; } var tdEl = document.createElement('td'); tdEl.textContent = total; trEl.appendChild(tdEl); dailyTotalAllLocations += total; // trEl.appendChild(thEl); } tdEl = document.createElement('td'); tdEl.textContent = dailyTotalAllLocations; trEl.appendChild(tdEl); tfootEl.appendChild(trEl); myTable.appendChild(tfootEl); } function removeFooter(){ var footerRef = document.getElementById('tableFooter'); if (footerRef !== null){ footerRef.parentElement.removeChild(footerRef); } } //event listener function makeStore(event){ event.preventDefault(); myTable.innerHtml = ''; var name = event.target.name.value; var minCust = parseInt(event.target.minCust.value); var maxCust = parseInt(event.target.maxCust.value); var avgCookieSale = parseFloat(event.target.avgCookieSale.value); var addStore = new Store(name, minCust, maxCust, avgCookieSale); event.target.name.value = null; event.target.minCust.value = null; event.target.maxCust.value = null; event.target.avgCookieSale.value = null; addStore.render(); makeFooter(); console.log('first calls'); } //Variables ready to make the individual store objects var pikePlace = new Store('Pikes Market', 23, 65, 6.3); var seaTac = new Store ('Seatac', 3, 24, 1.2); var seaCent = new Store('Seattle Center', 11, 38, 3.7); var capHill = new Store('Capitol Hill', 30, 28, 2.3); var alki = new Store('Alki', 2, 16, 4.6); makeHeader(); renderAllLocations(); makeFooter(); console.log('last calls'); form.addEventListener('submit', makeStore);
{ var cust = Math.floor(Math.random() * (this.maxCust - this.minCust) + this.minCust); this.hourlyCust.push(cust); }
conditional_block
config.js
var args = require('yargs'); const dest = './dist'; const src = './src'; const port = 3000; const shouldWatch = args.watch; module.exports = { watch: shouldWatch, src: src, dest: dest, webpack: { entry: { bundle: src + '/bundles/bundle.js' },
} }, browserSync: { server: { baseDir: dest, port: port }//, //files: [dest + '/dist/**'] }, sass: { settings: { sourceComments: 'map', imagePath: '/img' // Used by the image-url helper } }, appx: { src: src + '/AppxManifest.xml' }, ngrok: { port: port }, production: { cssSrc: dest + '/**/*.css', jsSrc: dest + '/**/*.js', dest: dest }, clean: { src: dest }, deploy: { src: dest + '/**/*' } };
output: { filename: '[name].js', path: dest + '/bundles'
random_line_split
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ): Element | null /** * Find an element by a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first: true ): Element | null /** * Find all elements matching a given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first?: false ): Element[] /** * Find all elements matching a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first?: false ): Element[]
elm: Document | Element | string | string[], queries?: string | string[] | boolean, first?: boolean ): Element | Element[] | null { if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries)) { queries = queries.join(','); } const q = queries as string; return first ? elm.querySelector(q) : Array.from(elm.querySelectorAll(q)); } export default findByQuery;
function findByQuery(
random_line_split
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ): Element | null /** * Find an element by a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first: true ): Element | null /** * Find all elements matching a given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first?: false ): Element[] /** * Find all elements matching a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first?: false ): Element[] function
( elm: Document | Element | string | string[], queries?: string | string[] | boolean, first?: boolean ): Element | Element[] | null { if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries)) { queries = queries.join(','); } const q = queries as string; return first ? elm.querySelector(q) : Array.from(elm.querySelectorAll(q)); } export default findByQuery;
findByQuery
identifier_name
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ): Element | null /** * Find an element by a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first: true ): Element | null /** * Find all elements matching a given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first?: false ): Element[] /** * Find all elements matching a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first?: false ): Element[] function findByQuery( elm: Document | Element | string | string[], queries?: string | string[] | boolean, first?: boolean ): Element | Element[] | null
export default findByQuery;
{ if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries)) { queries = queries.join(','); } const q = queries as string; return first ? elm.querySelector(q) : Array.from(elm.querySelectorAll(q)); }
identifier_body
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ): Element | null /** * Find an element by a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first: true ): Element | null /** * Find all elements matching a given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first?: false ): Element[] /** * Find all elements matching a given CSS selector from within a given element * * @param elm - The DOM element to start the search from * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( elm: Document | Element, queries: string | string[], first?: false ): Element[] function findByQuery( elm: Document | Element | string | string[], queries?: string | string[] | boolean, first?: boolean ): Element | Element[] | null { if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries))
const q = queries as string; return first ? elm.querySelector(q) : Array.from(elm.querySelectorAll(q)); } export default findByQuery;
{ queries = queries.join(','); }
conditional_block
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Registry definition for fixture datasets.""" from flask.ext.registry import RegistryProxy from invenio.ext.registry import ModuleAutoDiscoveryRegistry from invenio.utils.datastructures import LazyDict fixtures_proxy = RegistryProxy( 'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures') def fixtures_loader():
fixtures = LazyDict(fixtures_loader)
"""Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)): if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data) return out
identifier_body
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Registry definition for fixture datasets.""" from flask.ext.registry import RegistryProxy from invenio.ext.registry import ModuleAutoDiscoveryRegistry from invenio.utils.datastructures import LazyDict fixtures_proxy = RegistryProxy( 'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures') def
(): """Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)): if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data) return out fixtures = LazyDict(fixtures_loader)
fixtures_loader
identifier_name
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Registry definition for fixture datasets.""" from flask.ext.registry import RegistryProxy from invenio.ext.registry import ModuleAutoDiscoveryRegistry from invenio.utils.datastructures import LazyDict
def fixtures_loader(): """Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)): if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data) return out fixtures = LazyDict(fixtures_loader)
fixtures_proxy = RegistryProxy( 'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures')
random_line_split
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Registry definition for fixture datasets.""" from flask.ext.registry import RegistryProxy from invenio.ext.registry import ModuleAutoDiscoveryRegistry from invenio.utils.datastructures import LazyDict fixtures_proxy = RegistryProxy( 'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures') def fixtures_loader(): """Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)):
return out fixtures = LazyDict(fixtures_loader)
if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data)
conditional_block
editor_plugin_src.js
/** * $RCSfile: editor_plugin_src.js,v $ * $Revision: 1.34 $ * $Date: 2006/02/10 16:29:39 $ * * @author Moxiecode * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved. */ /* Import plugin specific language pack */ tinyMCE.importPluginLanguagePack('flash', 'en,tr,de,sv,zh_cn,cs,fa,fr_ca,fr,pl,pt_br,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,zh_tw,zh_tw_utf8,sk,pt_br'); var TinyMCE_FlashPlugin = { getInfo : function() { return { longname : 'Flash', author : 'Moxiecode Systems', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_flash.html', version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion }; }, initInstance : function(inst) { if (!tinyMCE.settings['flash_skip_plugin_css']) tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/plugins/flash/css/content.css"); }, getControlHTML : function(cn) { switch (cn) { case "flash": return tinyMCE.getButtonHTML(cn, 'lang_flash_desc', '{$pluginurl}/images/flash.gif', 'mceFlash'); } return ""; }, execCommand : function(editor_id, element, command, user_interface, value) { // Handle commands switch (command) { case "mceFlash": var name = "", swffile = "", swfwidth = "", swfheight = "", action = "insert"; var template = new Array(); var inst = tinyMCE.getInstanceById(editor_id); var focusElm = inst.getFocusElement(); template['file'] = '../../plugins/flash/flash.htm'; // Relative to theme template['width'] = 430; template['height'] = 175; template['width'] += tinyMCE.getLang('lang_flash_delta_width', 0); template['height'] += tinyMCE.getLang('lang_flash_delta_height', 0); // Is selection a image if (focusElm != null && focusElm.nodeName.toLowerCase() == "img") { name = tinyMCE.getAttrib(focusElm, 'class'); if (name.indexOf('mceItemFlash') == -1) // Not a Flash return true; // Get rest of Flash items swffile = tinyMCE.getAttrib(focusElm, 'alt'); if (tinyMCE.getParam('convert_urls')) swffile = eval(tinyMCE.settings['urlconverter_callback'] + "(swffile, null, true);"); swfwidth = tinyMCE.getAttrib(focusElm, 'width'); swfheight = tinyMCE.getAttrib(focusElm, 'height'); action = "update"; } tinyMCE.openWindow(template, {editor_id : editor_id, inline : "yes", swffile : swffile, swfwidth : swfwidth, swfheight : swfheight, action : action}); return true; } // Pass to next handler in chain return false; }, cleanup : function(type, content) { switch (type) { case "insert_to_editor_dom": // Force relative/absolute if (tinyMCE.getParam('convert_urls')) { var imgs = content.getElementsByTagName("img"); for (var i=0; i<imgs.length; i++) { if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") { var src = tinyMCE.getAttrib(imgs[i], "alt"); if (tinyMCE.getParam('convert_urls')) src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);"); imgs[i].setAttribute('alt', src); imgs[i].setAttribute('title', src); } } } break; case "get_from_editor_dom": var imgs = content.getElementsByTagName("img"); for (var i=0; i<imgs.length; i++) { if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") { var src = tinyMCE.getAttrib(imgs[i], "alt"); if (tinyMCE.getParam('convert_urls')) src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);"); imgs[i].setAttribute('alt', src); imgs[i].setAttribute('title', src); } } break; case "insert_to_editor": var startPos = 0; var embedList = new Array(); // Fix the embed and object elements content = content.replace(new RegExp('<[ ]*embed','gi'),'<embed'); content = content.replace(new RegExp('<[ ]*/embed[ ]*>','gi'),'</embed>'); content = content.replace(new RegExp('<[ ]*object','gi'),'<object'); content = content.replace(new RegExp('<[ ]*/object[ ]*>','gi'),'</object>'); // Parse all embed tags while ((startPos = content.indexOf('<embed', startPos+1)) != -1) { var endPos = content.indexOf('>', startPos); var attribs = TinyMCE_FlashPlugin._parseAttributes(content.substring(startPos + 6, endPos)); embedList[embedList.length] = attribs; } // Parse all object tags and replace them with images from the embed data var index = 0; while ((startPos = content.indexOf('<object', startPos)) != -1) { if (index >= embedList.length) break; var attribs = embedList[index]; // Find end of object endPos = content.indexOf('</object>', startPos); endPos += 9; // Insert image var contentAfter = content.substring(endPos); content = content.substring(0, startPos); content += '<img width="' + attribs["width"] + '" height="' + attribs["height"] + '"'; content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + attribs["src"] + '"'; content += ' alt="' + attribs["src"] + '" class="mceItemFlash" />' + content.substring(endPos); content += contentAfter; index++; startPos++; } // Parse all embed tags and replace them with images from the embed data var index = 0; while ((startPos = content.indexOf('<embed', startPos)) != -1) { if (index >= embedList.length) break; var attribs = embedList[index]; // Find end of embed endPos = content.indexOf('>', startPos); endPos += 9; // Insert image var contentAfter = content.substring(endPos); content = content.substring(0, startPos); content += '<img width="' + attribs["width"] + '" height="' + attribs["height"] + '"'; content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + attribs["src"] + '"'; content += ' alt="' + attribs["src"] + '" class="mceItemFlash" />' + content.substring(endPos); content += contentAfter; index++; startPos++; } break; case "get_from_editor": // Parse all img tags and replace them with object+embed var startPos = -1; while ((startPos = content.indexOf('<img', startPos+1)) != -1) { var endPos = content.indexOf('/>', startPos); var attribs = TinyMCE_FlashPlugin._parseAttributes(content.substring(startPos + 4, endPos)); // Is not flash, skip it if (attribs['class'] != "mceItemFlash") continue; endPos += 2; var embedHTML = ''; var wmode = tinyMCE.getParam("flash_wmode", ""); var quality = tinyMCE.getParam("flash_quality", "high"); var menu = tinyMCE.getParam("flash_menu", "false"); // Insert object + embed embedHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'; embedHTML += ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"'; embedHTML += ' width="' + attribs["width"] + '" height="' + attribs["height"] + '">'; embedHTML += '<param name="movie" value="' + attribs["title"] + '" />'; embedHTML += '<param name="quality" value="' + quality + '" />'; embedHTML += '<param name="menu" value="' + menu + '" />'; embedHTML += '<param name="wmode" value="' + wmode + '" />'; embedHTML += '<embed src="' + attribs["title"] + '" wmode="' + wmode + '" quality="' + quality + '" menu="' + menu + '" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + attribs["width"] + '" height="' + attribs["height"] + '"></embed></object>'; // Insert embed/object chunk chunkBefore = content.substring(0, startPos); chunkAfter = content.substring(endPos); content = chunkBefore + embedHTML + chunkAfter; } break; } // Pass through to next handler in chain return content; }, handleNodeChange : function(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) { if (node == null) return; do { if (node.nodeName == "IMG" && tinyMCE.getAttrib(node, 'class').indexOf('mceItemFlash') == 0) {
} while ((node = node.parentNode)); tinyMCE.switchClass(editor_id + '_flash', 'mceButtonNormal'); return true; }, // Private plugin internal functions _parseAttributes : function(attribute_string) { var attributeName = ""; var attributeValue = ""; var withInName; var withInValue; var attributes = new Array(); var whiteSpaceRegExp = new RegExp('^[ \n\r\t]+', 'g'); if (attribute_string == null || attribute_string.length < 2) return null; withInName = withInValue = false; for (var i=0; i<attribute_string.length; i++) { var chr = attribute_string.charAt(i); if ((chr == '"' || chr == "'") && !withInValue) withInValue = true; else if ((chr == '"' || chr == "'") && withInValue) { withInValue = false; var pos = attributeName.lastIndexOf(' '); if (pos != -1) attributeName = attributeName.substring(pos+1); attributes[attributeName.toLowerCase()] = attributeValue.substring(1); attributeName = ""; attributeValue = ""; } else if (!whiteSpaceRegExp.test(chr) && !withInName && !withInValue) withInName = true; if (chr == '=' && withInName) withInName = false; if (withInName) attributeName += chr; if (withInValue) attributeValue += chr; } return attributes; } }; tinyMCE.addPlugin("flash", TinyMCE_FlashPlugin);
tinyMCE.switchClass(editor_id + '_flash', 'mceButtonSelected'); return true; }
conditional_block
editor_plugin_src.js
/** * $RCSfile: editor_plugin_src.js,v $ * $Revision: 1.34 $ * $Date: 2006/02/10 16:29:39 $ * * @author Moxiecode * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved. */ /* Import plugin specific language pack */ tinyMCE.importPluginLanguagePack('flash', 'en,tr,de,sv,zh_cn,cs,fa,fr_ca,fr,pl,pt_br,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,zh_tw,zh_tw_utf8,sk,pt_br'); var TinyMCE_FlashPlugin = { getInfo : function() { return { longname : 'Flash', author : 'Moxiecode Systems', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_flash.html', version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion }; }, initInstance : function(inst) { if (!tinyMCE.settings['flash_skip_plugin_css']) tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/plugins/flash/css/content.css"); }, getControlHTML : function(cn) { switch (cn) { case "flash": return tinyMCE.getButtonHTML(cn, 'lang_flash_desc', '{$pluginurl}/images/flash.gif', 'mceFlash'); } return ""; }, execCommand : function(editor_id, element, command, user_interface, value) { // Handle commands switch (command) { case "mceFlash": var name = "", swffile = "", swfwidth = "", swfheight = "", action = "insert"; var template = new Array(); var inst = tinyMCE.getInstanceById(editor_id); var focusElm = inst.getFocusElement(); template['file'] = '../../plugins/flash/flash.htm'; // Relative to theme template['width'] = 430; template['height'] = 175; template['width'] += tinyMCE.getLang('lang_flash_delta_width', 0); template['height'] += tinyMCE.getLang('lang_flash_delta_height', 0); // Is selection a image if (focusElm != null && focusElm.nodeName.toLowerCase() == "img") { name = tinyMCE.getAttrib(focusElm, 'class'); if (name.indexOf('mceItemFlash') == -1) // Not a Flash return true; // Get rest of Flash items swffile = tinyMCE.getAttrib(focusElm, 'alt'); if (tinyMCE.getParam('convert_urls')) swffile = eval(tinyMCE.settings['urlconverter_callback'] + "(swffile, null, true);"); swfwidth = tinyMCE.getAttrib(focusElm, 'width'); swfheight = tinyMCE.getAttrib(focusElm, 'height'); action = "update"; } tinyMCE.openWindow(template, {editor_id : editor_id, inline : "yes", swffile : swffile, swfwidth : swfwidth, swfheight : swfheight, action : action}); return true; } // Pass to next handler in chain return false; }, cleanup : function(type, content) { switch (type) { case "insert_to_editor_dom": // Force relative/absolute if (tinyMCE.getParam('convert_urls')) { var imgs = content.getElementsByTagName("img"); for (var i=0; i<imgs.length; i++) { if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") { var src = tinyMCE.getAttrib(imgs[i], "alt");
imgs[i].setAttribute('alt', src); imgs[i].setAttribute('title', src); } } } break; case "get_from_editor_dom": var imgs = content.getElementsByTagName("img"); for (var i=0; i<imgs.length; i++) { if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") { var src = tinyMCE.getAttrib(imgs[i], "alt"); if (tinyMCE.getParam('convert_urls')) src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);"); imgs[i].setAttribute('alt', src); imgs[i].setAttribute('title', src); } } break; case "insert_to_editor": var startPos = 0; var embedList = new Array(); // Fix the embed and object elements content = content.replace(new RegExp('<[ ]*embed','gi'),'<embed'); content = content.replace(new RegExp('<[ ]*/embed[ ]*>','gi'),'</embed>'); content = content.replace(new RegExp('<[ ]*object','gi'),'<object'); content = content.replace(new RegExp('<[ ]*/object[ ]*>','gi'),'</object>'); // Parse all embed tags while ((startPos = content.indexOf('<embed', startPos+1)) != -1) { var endPos = content.indexOf('>', startPos); var attribs = TinyMCE_FlashPlugin._parseAttributes(content.substring(startPos + 6, endPos)); embedList[embedList.length] = attribs; } // Parse all object tags and replace them with images from the embed data var index = 0; while ((startPos = content.indexOf('<object', startPos)) != -1) { if (index >= embedList.length) break; var attribs = embedList[index]; // Find end of object endPos = content.indexOf('</object>', startPos); endPos += 9; // Insert image var contentAfter = content.substring(endPos); content = content.substring(0, startPos); content += '<img width="' + attribs["width"] + '" height="' + attribs["height"] + '"'; content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + attribs["src"] + '"'; content += ' alt="' + attribs["src"] + '" class="mceItemFlash" />' + content.substring(endPos); content += contentAfter; index++; startPos++; } // Parse all embed tags and replace them with images from the embed data var index = 0; while ((startPos = content.indexOf('<embed', startPos)) != -1) { if (index >= embedList.length) break; var attribs = embedList[index]; // Find end of embed endPos = content.indexOf('>', startPos); endPos += 9; // Insert image var contentAfter = content.substring(endPos); content = content.substring(0, startPos); content += '<img width="' + attribs["width"] + '" height="' + attribs["height"] + '"'; content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + attribs["src"] + '"'; content += ' alt="' + attribs["src"] + '" class="mceItemFlash" />' + content.substring(endPos); content += contentAfter; index++; startPos++; } break; case "get_from_editor": // Parse all img tags and replace them with object+embed var startPos = -1; while ((startPos = content.indexOf('<img', startPos+1)) != -1) { var endPos = content.indexOf('/>', startPos); var attribs = TinyMCE_FlashPlugin._parseAttributes(content.substring(startPos + 4, endPos)); // Is not flash, skip it if (attribs['class'] != "mceItemFlash") continue; endPos += 2; var embedHTML = ''; var wmode = tinyMCE.getParam("flash_wmode", ""); var quality = tinyMCE.getParam("flash_quality", "high"); var menu = tinyMCE.getParam("flash_menu", "false"); // Insert object + embed embedHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'; embedHTML += ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"'; embedHTML += ' width="' + attribs["width"] + '" height="' + attribs["height"] + '">'; embedHTML += '<param name="movie" value="' + attribs["title"] + '" />'; embedHTML += '<param name="quality" value="' + quality + '" />'; embedHTML += '<param name="menu" value="' + menu + '" />'; embedHTML += '<param name="wmode" value="' + wmode + '" />'; embedHTML += '<embed src="' + attribs["title"] + '" wmode="' + wmode + '" quality="' + quality + '" menu="' + menu + '" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + attribs["width"] + '" height="' + attribs["height"] + '"></embed></object>'; // Insert embed/object chunk chunkBefore = content.substring(0, startPos); chunkAfter = content.substring(endPos); content = chunkBefore + embedHTML + chunkAfter; } break; } // Pass through to next handler in chain return content; }, handleNodeChange : function(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) { if (node == null) return; do { if (node.nodeName == "IMG" && tinyMCE.getAttrib(node, 'class').indexOf('mceItemFlash') == 0) { tinyMCE.switchClass(editor_id + '_flash', 'mceButtonSelected'); return true; } } while ((node = node.parentNode)); tinyMCE.switchClass(editor_id + '_flash', 'mceButtonNormal'); return true; }, // Private plugin internal functions _parseAttributes : function(attribute_string) { var attributeName = ""; var attributeValue = ""; var withInName; var withInValue; var attributes = new Array(); var whiteSpaceRegExp = new RegExp('^[ \n\r\t]+', 'g'); if (attribute_string == null || attribute_string.length < 2) return null; withInName = withInValue = false; for (var i=0; i<attribute_string.length; i++) { var chr = attribute_string.charAt(i); if ((chr == '"' || chr == "'") && !withInValue) withInValue = true; else if ((chr == '"' || chr == "'") && withInValue) { withInValue = false; var pos = attributeName.lastIndexOf(' '); if (pos != -1) attributeName = attributeName.substring(pos+1); attributes[attributeName.toLowerCase()] = attributeValue.substring(1); attributeName = ""; attributeValue = ""; } else if (!whiteSpaceRegExp.test(chr) && !withInName && !withInValue) withInName = true; if (chr == '=' && withInName) withInName = false; if (withInName) attributeName += chr; if (withInValue) attributeValue += chr; } return attributes; } }; tinyMCE.addPlugin("flash", TinyMCE_FlashPlugin);
if (tinyMCE.getParam('convert_urls')) src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);");
random_line_split
DataTypeMapIntFloat.py
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def
(xs): return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}}
to_objectset
identifier_name
DataTypeMapIntFloat.py
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual
return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}}
c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs):
random_line_split
DataTypeMapIntFloat.py
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs):
assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}}
return set([frozenset(x.items()) for x in xs])
identifier_body
adminMenu.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import { visitDashboard } from '@web-stories-wp/e2e-test-utils'; describe('Admin Menu', () => { // eslint-disable-next-line jest/no-disabled-tests -- broken by https://github.com/googleforcreators/web-stories-wp/pull/7213, needs updating. it.skip('should sync the WP nav with the dashboard nav', async () => { await visitDashboard(); // Initial visit to `/` makes `Dashboard` link current in WP await page.hover('#menu-posts-web-story'); await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch( 'Dashboard' ); await page.hover('[aria-label="Main dashboard navigation"]'); // Navigating through the application to a new page syncs the WP current page in Nav await page.waitForTimeout(100); await Promise.all([ page.waitForNavigation(), expect(page).toClick('[aria-label="Main dashboard navigation"] a', { text: 'Explore Templates', }), ]); await page.waitForTimeout(100); await page.hover('#menu-posts-web-story'); await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch( 'Explore Templates' ); await page.hover('[aria-label="Main dashboard navigation"]'); // Navigating through WP to a new page syncs the WP current page in Nav await page.hover('#menu-posts-web-story'); await page.waitForTimeout(100); await Promise.all([ page.waitForNavigation(), expect(page).toClick('#menu-posts-web-story a', { text: 'Settings', }), ]); await page.waitForTimeout(100); await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch( 'Settings' ); // await page.hover('[aria-label="Main dashboard navigation"]'); // Navigating through application back to My Story from another route await page.waitForTimeout(100); await Promise.all([ page.waitForNavigation(), expect(page).toClick('[aria-label="Main dashboard navigation"] a', { text: 'Dashboard', }), ]); await page.waitForTimeout(100); await page.hover('#menu-posts-web-story'); await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch( 'Dashboard' ); }); });
* https://www.apache.org/licenses/LICENSE-2.0
random_line_split
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `storageService` // interface, and provide our custom implementation, // which will default to `true` for the correct string-key. // unfortunately, while the typescript-interface exists, // it is not exported from monaco-editor, // so we cannot rely on typescript to make sure // we do it right. all we can do is to manually // lookup the interface, and make sure we code our code right. // our code is a "best effort" approach, // i am not 100% how the `scope` and `target` things work, // but so far it seems to work ok. // i would use an another approach, if there was one available. function makeStorageService() { // we need to return an object that fulfills this interface: // https://github.com/microsoft/vscode/blob/ff1e16eebb93af79fd6d7af1356c4003a120c563/src/vs/platform/storage/common/storage.ts#L37 // unfortunately it is not export from monaco-editor const strings = new Map<string, string>(); // we want this to be true by default strings.set('expandSuggestionDocs', true.toString()); return { // we do not implement the on* handlers onDidChangeValue: (data: unknown): void => undefined, onDidChangeTarget: (data: unknown): void => undefined, onWillSaveState: (data: unknown): void => undefined, get: (key: string, scope: unknown, fallbackValue?: string): string | undefined => { return strings.get(key) ?? fallbackValue; }, getBoolean: (key: string, scope: unknown, fallbackValue?: boolean): boolean | undefined => { const val = strings.get(key); if (val !== undefined) { // the interface-docs say the value will be converted // to a boolean but do not specify how, so we improvise return val === 'true'; } else { return fallbackValue; } }, getNumber: (key: string, scope: unknown, fallbackValue?: number): number | undefined => { const val = strings.get(key); if (val !== undefined) { return parseInt(val, 10); } else { return fallbackValue; } }, store: ( key: string, value: string | boolean | number | undefined | null, scope: unknown, target: unknown ): void => { // the interface-docs say if the value is nullish, it should act as delete if (value === null || value === undefined) { strings.delete(key); } else
}, remove: (key: string, scope: unknown): void => { strings.delete(key); }, keys: (scope: unknown, target: unknown): string[] => { return Array.from(strings.keys()); }, logStorage: (): void => { console.log('logStorage: not implemented'); }, migrate: (): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, isNew: (scope: unknown): boolean => { // we create a new storage for every session, we do not persist it, // so we return `true`. return true; }, flush: (reason?: unknown): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, }; } let overrideServices: monacoTypes.editor.IEditorOverrideServices | null = null; export function getOverrideServices(): monacoTypes.editor.IEditorOverrideServices { // only have one instance of this for every query editor if (overrideServices === null) { overrideServices = { storageService: makeStorageService(), }; } return overrideServices; }
{ strings.set(key, value.toString()); }
conditional_block
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `storageService` // interface, and provide our custom implementation, // which will default to `true` for the correct string-key. // unfortunately, while the typescript-interface exists, // it is not exported from monaco-editor, // so we cannot rely on typescript to make sure // we do it right. all we can do is to manually // lookup the interface, and make sure we code our code right. // our code is a "best effort" approach, // i am not 100% how the `scope` and `target` things work, // but so far it seems to work ok. // i would use an another approach, if there was one available. function makeStorageService() { // we need to return an object that fulfills this interface: // https://github.com/microsoft/vscode/blob/ff1e16eebb93af79fd6d7af1356c4003a120c563/src/vs/platform/storage/common/storage.ts#L37 // unfortunately it is not export from monaco-editor const strings = new Map<string, string>(); // we want this to be true by default strings.set('expandSuggestionDocs', true.toString()); return { // we do not implement the on* handlers onDidChangeValue: (data: unknown): void => undefined, onDidChangeTarget: (data: unknown): void => undefined, onWillSaveState: (data: unknown): void => undefined, get: (key: string, scope: unknown, fallbackValue?: string): string | undefined => { return strings.get(key) ?? fallbackValue; }, getBoolean: (key: string, scope: unknown, fallbackValue?: boolean): boolean | undefined => { const val = strings.get(key); if (val !== undefined) { // the interface-docs say the value will be converted // to a boolean but do not specify how, so we improvise return val === 'true'; } else { return fallbackValue; } }, getNumber: (key: string, scope: unknown, fallbackValue?: number): number | undefined => { const val = strings.get(key); if (val !== undefined) { return parseInt(val, 10); } else { return fallbackValue; } }, store: ( key: string, value: string | boolean | number | undefined | null, scope: unknown, target: unknown ): void => { // the interface-docs say if the value is nullish, it should act as delete if (value === null || value === undefined) { strings.delete(key); } else { strings.set(key, value.toString()); } }, remove: (key: string, scope: unknown): void => { strings.delete(key); }, keys: (scope: unknown, target: unknown): string[] => { return Array.from(strings.keys()); }, logStorage: (): void => { console.log('logStorage: not implemented'); }, migrate: (): Promise<void> => { // we do not implement this return Promise.resolve(undefined); },
// we create a new storage for every session, we do not persist it, // so we return `true`. return true; }, flush: (reason?: unknown): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, }; } let overrideServices: monacoTypes.editor.IEditorOverrideServices | null = null; export function getOverrideServices(): monacoTypes.editor.IEditorOverrideServices { // only have one instance of this for every query editor if (overrideServices === null) { overrideServices = { storageService: makeStorageService(), }; } return overrideServices; }
isNew: (scope: unknown): boolean => {
random_line_split
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `storageService` // interface, and provide our custom implementation, // which will default to `true` for the correct string-key. // unfortunately, while the typescript-interface exists, // it is not exported from monaco-editor, // so we cannot rely on typescript to make sure // we do it right. all we can do is to manually // lookup the interface, and make sure we code our code right. // our code is a "best effort" approach, // i am not 100% how the `scope` and `target` things work, // but so far it seems to work ok. // i would use an another approach, if there was one available. function makeStorageService() { // we need to return an object that fulfills this interface: // https://github.com/microsoft/vscode/blob/ff1e16eebb93af79fd6d7af1356c4003a120c563/src/vs/platform/storage/common/storage.ts#L37 // unfortunately it is not export from monaco-editor const strings = new Map<string, string>(); // we want this to be true by default strings.set('expandSuggestionDocs', true.toString()); return { // we do not implement the on* handlers onDidChangeValue: (data: unknown): void => undefined, onDidChangeTarget: (data: unknown): void => undefined, onWillSaveState: (data: unknown): void => undefined, get: (key: string, scope: unknown, fallbackValue?: string): string | undefined => { return strings.get(key) ?? fallbackValue; }, getBoolean: (key: string, scope: unknown, fallbackValue?: boolean): boolean | undefined => { const val = strings.get(key); if (val !== undefined) { // the interface-docs say the value will be converted // to a boolean but do not specify how, so we improvise return val === 'true'; } else { return fallbackValue; } }, getNumber: (key: string, scope: unknown, fallbackValue?: number): number | undefined => { const val = strings.get(key); if (val !== undefined) { return parseInt(val, 10); } else { return fallbackValue; } }, store: ( key: string, value: string | boolean | number | undefined | null, scope: unknown, target: unknown ): void => { // the interface-docs say if the value is nullish, it should act as delete if (value === null || value === undefined) { strings.delete(key); } else { strings.set(key, value.toString()); } }, remove: (key: string, scope: unknown): void => { strings.delete(key); }, keys: (scope: unknown, target: unknown): string[] => { return Array.from(strings.keys()); }, logStorage: (): void => { console.log('logStorage: not implemented'); }, migrate: (): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, isNew: (scope: unknown): boolean => { // we create a new storage for every session, we do not persist it, // so we return `true`. return true; }, flush: (reason?: unknown): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, }; } let overrideServices: monacoTypes.editor.IEditorOverrideServices | null = null; export function
(): monacoTypes.editor.IEditorOverrideServices { // only have one instance of this for every query editor if (overrideServices === null) { overrideServices = { storageService: makeStorageService(), }; } return overrideServices; }
getOverrideServices
identifier_name
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `storageService` // interface, and provide our custom implementation, // which will default to `true` for the correct string-key. // unfortunately, while the typescript-interface exists, // it is not exported from monaco-editor, // so we cannot rely on typescript to make sure // we do it right. all we can do is to manually // lookup the interface, and make sure we code our code right. // our code is a "best effort" approach, // i am not 100% how the `scope` and `target` things work, // but so far it seems to work ok. // i would use an another approach, if there was one available. function makeStorageService()
let overrideServices: monacoTypes.editor.IEditorOverrideServices | null = null; export function getOverrideServices(): monacoTypes.editor.IEditorOverrideServices { // only have one instance of this for every query editor if (overrideServices === null) { overrideServices = { storageService: makeStorageService(), }; } return overrideServices; }
{ // we need to return an object that fulfills this interface: // https://github.com/microsoft/vscode/blob/ff1e16eebb93af79fd6d7af1356c4003a120c563/src/vs/platform/storage/common/storage.ts#L37 // unfortunately it is not export from monaco-editor const strings = new Map<string, string>(); // we want this to be true by default strings.set('expandSuggestionDocs', true.toString()); return { // we do not implement the on* handlers onDidChangeValue: (data: unknown): void => undefined, onDidChangeTarget: (data: unknown): void => undefined, onWillSaveState: (data: unknown): void => undefined, get: (key: string, scope: unknown, fallbackValue?: string): string | undefined => { return strings.get(key) ?? fallbackValue; }, getBoolean: (key: string, scope: unknown, fallbackValue?: boolean): boolean | undefined => { const val = strings.get(key); if (val !== undefined) { // the interface-docs say the value will be converted // to a boolean but do not specify how, so we improvise return val === 'true'; } else { return fallbackValue; } }, getNumber: (key: string, scope: unknown, fallbackValue?: number): number | undefined => { const val = strings.get(key); if (val !== undefined) { return parseInt(val, 10); } else { return fallbackValue; } }, store: ( key: string, value: string | boolean | number | undefined | null, scope: unknown, target: unknown ): void => { // the interface-docs say if the value is nullish, it should act as delete if (value === null || value === undefined) { strings.delete(key); } else { strings.set(key, value.toString()); } }, remove: (key: string, scope: unknown): void => { strings.delete(key); }, keys: (scope: unknown, target: unknown): string[] => { return Array.from(strings.keys()); }, logStorage: (): void => { console.log('logStorage: not implemented'); }, migrate: (): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, isNew: (scope: unknown): boolean => { // we create a new storage for every session, we do not persist it, // so we return `true`. return true; }, flush: (reason?: unknown): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, }; }
identifier_body
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn
() { match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); } } }
main
identifier_name
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn main() { match vec!(1, 2, 3) { x =>
} }
{ assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); }
conditional_block
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn main()
{ match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); } } }
identifier_body
match-vec-rvalue.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. // Tests that matching rvalues with drops does not crash. // pretty-expanded FIXME #23616 pub fn main() { match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3);
assert_eq!(x[2], 3); } } }
assert_eq!(x[0], 1); assert_eq!(x[1], 2);
random_line_split
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer
class AccountCreateView(generics.CreateAPIView): queryset = Account.objects.all() serializer_class = AccountCreateSerializer permission_classes = [permissions.AllowAny] class AccountListView(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [permissions.IsAuthenticated] class AccountRetrieveView(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class AccountAuthenticationView(views.APIView): queryset = Account.objects.all() serializer_class = AuthenticateSerializer def post(self, request): data = request.data serializer = AuthenticateSerializer(data=data) if serializer.is_valid(raise_exception=True): new_date = serializer.data return response.Response(new_date,status=status.HTTP_200_OK) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# Create your views here.
random_line_split