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
CheckboxSelectionModel.js
/*! * js-file-browser * Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file. * * With components from: Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.grid.CheckboxSelectionModel * @extends Ext.grid.RowSelectionModel * A custom selection model that renders a column of checkboxes that can be toggled to select or deselect rows. * @constructor * @param {Object} config The configuration options */ Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { /** * @cfg {Boolean} checkOnly <tt>true</tt> if rows can only be selected by clicking on the * checkbox column (defaults to <tt>false</tt>). */ /** * @cfg {String} header Any valid text or HTML fragment to display in the header cell for the * checkbox column. Defaults to:<pre><code> * '&lt;div class="x-grid3-hd-checker">&#38;#160;&lt;/div>'</tt> * </code></pre> * The default CSS class of <tt>'x-grid3-hd-checker'</tt> displays a checkbox in the header * and provides support for automatic check all/none behavior on header click. This string * can be replaced by any valid HTML fragment, including a simple text string (e.g., * <tt>'Select Rows'</tt>), but the automatic check all/none behavior will only work if the * <tt>'x-grid3-hd-checker'</tt> class is supplied. */ header : '<div class="x-grid3-hd-checker">&#160;</div>', /** * @cfg {Number} width The default width in pixels of the checkbox column (defaults to <tt>20</tt>). */ width : 20, /** * @cfg {Boolean} sortable <tt>true</tt> if the checkbox column is sortable (defaults to * <tt>false</tt>). */ sortable : false, // private menuDisabled : true, fixed : true, hideable: false, dataIndex : '', id : 'checker', isColumn: true, // So that ColumnModel doesn't feed this through the Column constructor constructor : function(){ Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this, arguments); if(this.checkOnly){ this.handleMouseDown = Ext.emptyFn; } }, // private initEvents : function(){ Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); this.grid.on('render', function(){ Ext.fly(this.grid.getView().innerHd).on('mousedown', this.onHdMouseDown, this); }, this); }, /** * @private * Process and refire events routed from the GridView's processEvent method. */ processEvent : function(name, e, grid, rowIndex, colIndex){ if (name == 'mousedown') { this.onMouseDown(e, e.getTarget()); return false; } else
}, // private onMouseDown : function(e, t){ if(e.button === 0 && t.className == 'x-grid3-row-checker'){ // Only fire if left-click e.stopEvent(); var row = e.getTarget('.x-grid3-row'); if(row){ var index = row.rowIndex; if(this.isSelected(index)){ this.deselectRow(index); }else{ this.selectRow(index, true); this.grid.getView().focusRow(index); } } } }, // private onHdMouseDown : function(e, t) { if(t.className == 'x-grid3-hd-checker'){ e.stopEvent(); var hd = Ext.fly(t.parentNode); var isChecked = hd.hasClass('x-grid3-hd-checker-on'); if(isChecked){ hd.removeClass('x-grid3-hd-checker-on'); this.clearSelections(); }else{ hd.addClass('x-grid3-hd-checker-on'); this.selectAll(); } } }, // private renderer : function(v, p, record){ return '<div class="x-grid3-row-checker">&#160;</div>'; }, onEditorSelect: function(row, lastRow){ if(lastRow != row && !this.checkOnly){ this.selectRow(row); // *** highlight newly-selected cell and update selection } } });
{ return Ext.grid.Column.prototype.processEvent.apply(this, arguments); }
conditional_block
CheckboxSelectionModel.js
/*! * js-file-browser * Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file. * * With components from: Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.grid.CheckboxSelectionModel * @extends Ext.grid.RowSelectionModel * A custom selection model that renders a column of checkboxes that can be toggled to select or deselect rows. * @constructor * @param {Object} config The configuration options */ Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { /** * @cfg {Boolean} checkOnly <tt>true</tt> if rows can only be selected by clicking on the * checkbox column (defaults to <tt>false</tt>). */ /** * @cfg {String} header Any valid text or HTML fragment to display in the header cell for the * checkbox column. Defaults to:<pre><code> * '&lt;div class="x-grid3-hd-checker">&#38;#160;&lt;/div>'</tt> * </code></pre> * The default CSS class of <tt>'x-grid3-hd-checker'</tt> displays a checkbox in the header * and provides support for automatic check all/none behavior on header click. This string * can be replaced by any valid HTML fragment, including a simple text string (e.g., * <tt>'Select Rows'</tt>), but the automatic check all/none behavior will only work if the * <tt>'x-grid3-hd-checker'</tt> class is supplied. */ header : '<div class="x-grid3-hd-checker">&#160;</div>', /** * @cfg {Number} width The default width in pixels of the checkbox column (defaults to <tt>20</tt>). */ width : 20, /** * @cfg {Boolean} sortable <tt>true</tt> if the checkbox column is sortable (defaults to * <tt>false</tt>). */ sortable : false, // private menuDisabled : true, fixed : true, hideable: false, dataIndex : '', id : 'checker', isColumn: true, // So that ColumnModel doesn't feed this through the Column constructor constructor : function(){ Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this, arguments); if(this.checkOnly){ this.handleMouseDown = Ext.emptyFn; }
Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); this.grid.on('render', function(){ Ext.fly(this.grid.getView().innerHd).on('mousedown', this.onHdMouseDown, this); }, this); }, /** * @private * Process and refire events routed from the GridView's processEvent method. */ processEvent : function(name, e, grid, rowIndex, colIndex){ if (name == 'mousedown') { this.onMouseDown(e, e.getTarget()); return false; } else { return Ext.grid.Column.prototype.processEvent.apply(this, arguments); } }, // private onMouseDown : function(e, t){ if(e.button === 0 && t.className == 'x-grid3-row-checker'){ // Only fire if left-click e.stopEvent(); var row = e.getTarget('.x-grid3-row'); if(row){ var index = row.rowIndex; if(this.isSelected(index)){ this.deselectRow(index); }else{ this.selectRow(index, true); this.grid.getView().focusRow(index); } } } }, // private onHdMouseDown : function(e, t) { if(t.className == 'x-grid3-hd-checker'){ e.stopEvent(); var hd = Ext.fly(t.parentNode); var isChecked = hd.hasClass('x-grid3-hd-checker-on'); if(isChecked){ hd.removeClass('x-grid3-hd-checker-on'); this.clearSelections(); }else{ hd.addClass('x-grid3-hd-checker-on'); this.selectAll(); } } }, // private renderer : function(v, p, record){ return '<div class="x-grid3-row-checker">&#160;</div>'; }, onEditorSelect: function(row, lastRow){ if(lastRow != row && !this.checkOnly){ this.selectRow(row); // *** highlight newly-selected cell and update selection } } });
}, // private initEvents : function(){
random_line_split
test_compact_csv_reader.py
from __future__ import unicode_literals from django.utils import six import pytest from nicedjango.utils.compact_csv import CsvReader @pytest.fixture def stream(): csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8') return six.StringIO(csv) def test_reader_raw(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(), replace_digits=False) assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']] def test_reader_none(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, replace_digits=False)
assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']] def test_reader_quotes(stream): r = CsvReader(stream, replacements=(), replace_digits=False) assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']] def test_reader_replace(stream): r = CsvReader(stream, replace_digits=False) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']] def test_reader_replace_digit(stream): r = CsvReader(stream) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
random_line_split
test_compact_csv_reader.py
from __future__ import unicode_literals from django.utils import six import pytest from nicedjango.utils.compact_csv import CsvReader @pytest.fixture def stream(): csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8') return six.StringIO(csv) def
(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(), replace_digits=False) assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']] def test_reader_none(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, replace_digits=False) assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']] def test_reader_quotes(stream): r = CsvReader(stream, replacements=(), replace_digits=False) assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']] def test_reader_replace(stream): r = CsvReader(stream, replace_digits=False) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']] def test_reader_replace_digit(stream): r = CsvReader(stream) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
test_reader_raw
identifier_name
test_compact_csv_reader.py
from __future__ import unicode_literals from django.utils import six import pytest from nicedjango.utils.compact_csv import CsvReader @pytest.fixture def stream(): csv = b'''"a\xc2\x96b\\"c'd\\re\\nf,g\\\\",1,NULL,""\n'''.decode('utf-8') return six.StringIO(csv) def test_reader_raw(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(), replace_digits=False) assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', 'NULL', '""']] def test_reader_none(stream):
def test_reader_quotes(stream): r = CsvReader(stream, replacements=(), replace_digits=False) assert list(r) == [['''a\x96b\\"c'd\\re\\nf,g\\\\''', '1', None, '']] def test_reader_replace(stream): r = CsvReader(stream, replace_digits=False) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', '1', None, '']] def test_reader_replace_digit(stream): r = CsvReader(stream) assert list(r) == [['''a\x96b"c'd\re\nf,g\\''', 1, None, '']]
r = CsvReader(stream, replacements=(), preserve_quotes=True, replace_digits=False) assert list(r) == [['''"a\x96b\\"c'd\\re\\nf,g\\\\"''', '1', None, '""']]
identifier_body
layout_image.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread needs to be responsible for them because there's //! no guarantee that the responsible nodes will still exist in the future if the //! layout thread holds on to them during asynchronous operations. use dom::bindings::reflector::DomObject; use dom::node::{Node, document_from_node}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::{FetchResponseMsg, FetchResponseListener, FetchMetadata, NetworkError}; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Destination, RequestInit as FetchRequestInit}; use network_listener::{NetworkListener, PreInvoke}; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; struct
{ id: PendingImageId, cache: Arc<ImageCache>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache.notify_pending_response( self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache.notify_pending_response( self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } fn process_response_eof(&mut self, response: Result<(), NetworkError>) { self.cache.notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout(url: ServoUrl, node: &Node, id: PendingImageId, cache: Arc<ImageCache>) { let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, })); let document = document_from_node(node); let window = document.window(); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, task_source: window.networking_task_source(), canceller: Some(window.task_canceller()), }; ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); })); let request = FetchRequestInit { url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), .. FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document.loader().fetch_async_background(request, action_sender); }
LayoutImageContext
identifier_name
layout_image.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread needs to be responsible for them because there's //! no guarantee that the responsible nodes will still exist in the future if the //! layout thread holds on to them during asynchronous operations. use dom::bindings::reflector::DomObject; use dom::node::{Node, document_from_node}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::{FetchResponseMsg, FetchResponseListener, FetchMetadata, NetworkError}; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Destination, RequestInit as FetchRequestInit}; use network_listener::{NetworkListener, PreInvoke}; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; struct LayoutImageContext { id: PendingImageId, cache: Arc<ImageCache>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache.notify_pending_response( self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache.notify_pending_response( self.id, FetchResponseMsg::ProcessResponseChunk(payload)); } fn process_response_eof(&mut self, response: Result<(), NetworkError>) { self.cache.notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout(url: ServoUrl, node: &Node, id: PendingImageId, cache: Arc<ImageCache>)
{ let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, })); let document = document_from_node(node); let window = document.window(); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, task_source: window.networking_task_source(), canceller: Some(window.task_canceller()), }; ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); })); let request = FetchRequestInit { url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), .. FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document.loader().fetch_async_background(request, action_sender); }
identifier_body
layout_image.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread needs to be responsible for them because there's //! no guarantee that the responsible nodes will still exist in the future if the //! layout thread holds on to them during asynchronous operations. use dom::bindings::reflector::DomObject; use dom::node::{Node, document_from_node}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use net_traits::{FetchResponseMsg, FetchResponseListener, FetchMetadata, NetworkError}; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Destination, RequestInit as FetchRequestInit}; use network_listener::{NetworkListener, PreInvoke}; use servo_url::ServoUrl; use std::sync::{Arc, Mutex}; struct LayoutImageContext { id: PendingImageId, cache: Arc<ImageCache>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache.notify_pending_response( self.id, FetchResponseMsg::ProcessResponse(metadata)); } fn process_response_chunk(&mut self, payload: Vec<u8>) { self.cache.notify_pending_response( self.id,
} fn process_response_eof(&mut self, response: Result<(), NetworkError>) { self.cache.notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout(url: ServoUrl, node: &Node, id: PendingImageId, cache: Arc<ImageCache>) { let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, })); let document = document_from_node(node); let window = document.window(); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context, task_source: window.networking_task_source(), canceller: Some(window.task_canceller()), }; ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); })); let request = FetchRequestInit { url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), .. FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document.loader().fetch_async_background(request, action_sender); }
FetchResponseMsg::ProcessResponseChunk(payload));
random_line_split
http_shortcuts.py
from past.builtins import basestring import os.path import simplejson as json from django.shortcuts import render as django_render from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect from django.utils.decorators import available_attrs from functools import wraps def render(request, template, context = {}, ignore_ajax = False, obj=None, content_type=None, status=None, using=None): if request.is_ajax() and not ignore_ajax:
if not basename.startswith("_"): dirname = os.path.dirname(template) template = "%s/_%s"%(dirname,basename) response = django_render(request=request, template_name=template, context=context) else: response = django_render(request, template_name=template, context=context, content_type=content_type, status=status, using=using) return response def permanent_redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponsePermanentRedirect(to) else: return to return wrapper def redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponseRedirect(to) else: return to return wrapper def render_json(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kwargs): _json = view_func(request, *args, **kwargs) if not isinstance(_json, str) and not isinstance(_json, dict) and not isinstance(_json, list) and not isinstance(_json, tuple): return _json return HttpResponse(json.dumps(_json), content_type="application/json") return wrapper def render_to(template_name, ignore_ajax=False): def renderer(func): @wraps(func, assigned=available_attrs(func)) def wrapper(request, *args, **kw): output = func(request, *args, **kw) if not isinstance(output, dict): return output output['request'] = request return render(request, template=template_name, context=output, ignore_ajax=ignore_ajax) return wrapper return renderer
basename = os.path.basename(template)
random_line_split
http_shortcuts.py
from past.builtins import basestring import os.path import simplejson as json from django.shortcuts import render as django_render from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect from django.utils.decorators import available_attrs from functools import wraps def render(request, template, context = {}, ignore_ajax = False, obj=None, content_type=None, status=None, using=None): if request.is_ajax() and not ignore_ajax: basename = os.path.basename(template) if not basename.startswith("_"): dirname = os.path.dirname(template) template = "%s/_%s"%(dirname,basename) response = django_render(request=request, template_name=template, context=context) else: response = django_render(request, template_name=template, context=context, content_type=content_type, status=status, using=using) return response def permanent_redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponsePermanentRedirect(to) else: return to return wrapper def redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponseRedirect(to) else:
return wrapper def render_json(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kwargs): _json = view_func(request, *args, **kwargs) if not isinstance(_json, str) and not isinstance(_json, dict) and not isinstance(_json, list) and not isinstance(_json, tuple): return _json return HttpResponse(json.dumps(_json), content_type="application/json") return wrapper def render_to(template_name, ignore_ajax=False): def renderer(func): @wraps(func, assigned=available_attrs(func)) def wrapper(request, *args, **kw): output = func(request, *args, **kw) if not isinstance(output, dict): return output output['request'] = request return render(request, template=template_name, context=output, ignore_ajax=ignore_ajax) return wrapper return renderer
return to
conditional_block
http_shortcuts.py
from past.builtins import basestring import os.path import simplejson as json from django.shortcuts import render as django_render from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect from django.utils.decorators import available_attrs from functools import wraps def render(request, template, context = {}, ignore_ajax = False, obj=None, content_type=None, status=None, using=None): if request.is_ajax() and not ignore_ajax: basename = os.path.basename(template) if not basename.startswith("_"): dirname = os.path.dirname(template) template = "%s/_%s"%(dirname,basename) response = django_render(request=request, template_name=template, context=context) else: response = django_render(request, template_name=template, context=context, content_type=content_type, status=status, using=using) return response def permanent_redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponsePermanentRedirect(to) else: return to return wrapper def redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponseRedirect(to) else: return to return wrapper def render_json(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def
(request, *args, **kwargs): _json = view_func(request, *args, **kwargs) if not isinstance(_json, str) and not isinstance(_json, dict) and not isinstance(_json, list) and not isinstance(_json, tuple): return _json return HttpResponse(json.dumps(_json), content_type="application/json") return wrapper def render_to(template_name, ignore_ajax=False): def renderer(func): @wraps(func, assigned=available_attrs(func)) def wrapper(request, *args, **kw): output = func(request, *args, **kw) if not isinstance(output, dict): return output output['request'] = request return render(request, template=template_name, context=output, ignore_ajax=ignore_ajax) return wrapper return renderer
wrapper
identifier_name
http_shortcuts.py
from past.builtins import basestring import os.path import simplejson as json from django.shortcuts import render as django_render from django.http import HttpResponseRedirect, HttpResponse, HttpResponsePermanentRedirect from django.utils.decorators import available_attrs from functools import wraps def render(request, template, context = {}, ignore_ajax = False, obj=None, content_type=None, status=None, using=None):
def permanent_redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponsePermanentRedirect(to) else: return to return wrapper def redirect(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kw): to = view_func(request, *args, **kw) if isinstance(to, basestring): return HttpResponseRedirect(to) else: return to return wrapper def render_json(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def wrapper(request, *args, **kwargs): _json = view_func(request, *args, **kwargs) if not isinstance(_json, str) and not isinstance(_json, dict) and not isinstance(_json, list) and not isinstance(_json, tuple): return _json return HttpResponse(json.dumps(_json), content_type="application/json") return wrapper def render_to(template_name, ignore_ajax=False): def renderer(func): @wraps(func, assigned=available_attrs(func)) def wrapper(request, *args, **kw): output = func(request, *args, **kw) if not isinstance(output, dict): return output output['request'] = request return render(request, template=template_name, context=output, ignore_ajax=ignore_ajax) return wrapper return renderer
if request.is_ajax() and not ignore_ajax: basename = os.path.basename(template) if not basename.startswith("_"): dirname = os.path.dirname(template) template = "%s/_%s"%(dirname,basename) response = django_render(request=request, template_name=template, context=context) else: response = django_render(request, template_name=template, context=context, content_type=content_type, status=status, using=using) return response
identifier_body
node.py
# Ant # # Copyright (c) 2012, Gustav Tiger <gustav@tiger.name> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import collections import threading import logging import Queue from ant.base.ant import Ant from ant.base.message import Message from ant.easy.channel import Channel from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special _logger = logging.getLogger("garmin.ant.easy.node") class Node(): def __init__(self): self._responses_cond = threading.Condition() self._responses = collections.deque() self._event_cond = threading.Condition() self._events = collections.deque() self._datas = Queue.Queue() self.channels = {} self.ant = Ant() self._running = True self._worker_thread = threading.Thread(target=self._worker, name="ant.easy") self._worker_thread.start() def new_channel(self, ctype): channel = Channel(0, self, self.ant) self.channels[0] = channel channel._assign(ctype, 0x00) return channel def request_message(self, messageId): _logger.debug("requesting message %#02x", messageId) self.ant.request_message(0, messageId) _logger.debug("done requesting message %#02x", messageId) return self.wait_for_special(messageId) def set_network_key(self, network, key): self.ant.set_network_key(network, key) return self.wait_for_response(Message.ID.SET_NETWORK_KEY) def wait_for_event(self, ok_codes): return wait_for_event(ok_codes, self._events, self._event_cond) def wait_for_response(self, event_id): return wait_for_response(event_id, self._responses, self._responses_cond) def wait_for_special(self, event_id): return wait_for_special(event_id, self._responses, self._responses_cond) def _worker_response(self, channel, event, data): self._responses_cond.acquire() self._responses.append((channel, event, data)) self._responses_cond.notify() self._responses_cond.release() def _worker_event(self, channel, event, data): if event == Message.Code.EVENT_RX_BURST_PACKET: self._datas.put(('burst', channel, data)) elif event == Message.Code.EVENT_RX_BROADCAST: self._datas.put(('broadcast', channel, data)) else:
def _worker(self): self.ant.response_function = self._worker_response self.ant.channel_event_function = self._worker_event # TODO: check capabilities self.ant.start() def _main(self): while self._running: try: (data_type, channel, data) = self._datas.get(True, 1.0) self._datas.task_done() if data_type == 'broadcast': self.channels[channel].on_broadcast_data(data) elif data_type == 'burst': self.channels[channel].on_burst_data(data) else: _logger.warning("Unknown data type '%s': %r", data_type, data) except Queue.Empty as e: pass def start(self): self._main() def stop(self): if self._running: _logger.debug("Stoping ant.easy") self._running = False self.ant.stop() self._worker_thread.join()
self._event_cond.acquire() self._events.append((channel, event, data)) self._event_cond.notify() self._event_cond.release()
conditional_block
node.py
# Ant # # Copyright (c) 2012, Gustav Tiger <gustav@tiger.name> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import collections
import Queue from ant.base.ant import Ant from ant.base.message import Message from ant.easy.channel import Channel from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special _logger = logging.getLogger("garmin.ant.easy.node") class Node(): def __init__(self): self._responses_cond = threading.Condition() self._responses = collections.deque() self._event_cond = threading.Condition() self._events = collections.deque() self._datas = Queue.Queue() self.channels = {} self.ant = Ant() self._running = True self._worker_thread = threading.Thread(target=self._worker, name="ant.easy") self._worker_thread.start() def new_channel(self, ctype): channel = Channel(0, self, self.ant) self.channels[0] = channel channel._assign(ctype, 0x00) return channel def request_message(self, messageId): _logger.debug("requesting message %#02x", messageId) self.ant.request_message(0, messageId) _logger.debug("done requesting message %#02x", messageId) return self.wait_for_special(messageId) def set_network_key(self, network, key): self.ant.set_network_key(network, key) return self.wait_for_response(Message.ID.SET_NETWORK_KEY) def wait_for_event(self, ok_codes): return wait_for_event(ok_codes, self._events, self._event_cond) def wait_for_response(self, event_id): return wait_for_response(event_id, self._responses, self._responses_cond) def wait_for_special(self, event_id): return wait_for_special(event_id, self._responses, self._responses_cond) def _worker_response(self, channel, event, data): self._responses_cond.acquire() self._responses.append((channel, event, data)) self._responses_cond.notify() self._responses_cond.release() def _worker_event(self, channel, event, data): if event == Message.Code.EVENT_RX_BURST_PACKET: self._datas.put(('burst', channel, data)) elif event == Message.Code.EVENT_RX_BROADCAST: self._datas.put(('broadcast', channel, data)) else: self._event_cond.acquire() self._events.append((channel, event, data)) self._event_cond.notify() self._event_cond.release() def _worker(self): self.ant.response_function = self._worker_response self.ant.channel_event_function = self._worker_event # TODO: check capabilities self.ant.start() def _main(self): while self._running: try: (data_type, channel, data) = self._datas.get(True, 1.0) self._datas.task_done() if data_type == 'broadcast': self.channels[channel].on_broadcast_data(data) elif data_type == 'burst': self.channels[channel].on_burst_data(data) else: _logger.warning("Unknown data type '%s': %r", data_type, data) except Queue.Empty as e: pass def start(self): self._main() def stop(self): if self._running: _logger.debug("Stoping ant.easy") self._running = False self.ant.stop() self._worker_thread.join()
import threading import logging
random_line_split
node.py
# Ant # # Copyright (c) 2012, Gustav Tiger <gustav@tiger.name> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import collections import threading import logging import Queue from ant.base.ant import Ant from ant.base.message import Message from ant.easy.channel import Channel from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special _logger = logging.getLogger("garmin.ant.easy.node") class
(): def __init__(self): self._responses_cond = threading.Condition() self._responses = collections.deque() self._event_cond = threading.Condition() self._events = collections.deque() self._datas = Queue.Queue() self.channels = {} self.ant = Ant() self._running = True self._worker_thread = threading.Thread(target=self._worker, name="ant.easy") self._worker_thread.start() def new_channel(self, ctype): channel = Channel(0, self, self.ant) self.channels[0] = channel channel._assign(ctype, 0x00) return channel def request_message(self, messageId): _logger.debug("requesting message %#02x", messageId) self.ant.request_message(0, messageId) _logger.debug("done requesting message %#02x", messageId) return self.wait_for_special(messageId) def set_network_key(self, network, key): self.ant.set_network_key(network, key) return self.wait_for_response(Message.ID.SET_NETWORK_KEY) def wait_for_event(self, ok_codes): return wait_for_event(ok_codes, self._events, self._event_cond) def wait_for_response(self, event_id): return wait_for_response(event_id, self._responses, self._responses_cond) def wait_for_special(self, event_id): return wait_for_special(event_id, self._responses, self._responses_cond) def _worker_response(self, channel, event, data): self._responses_cond.acquire() self._responses.append((channel, event, data)) self._responses_cond.notify() self._responses_cond.release() def _worker_event(self, channel, event, data): if event == Message.Code.EVENT_RX_BURST_PACKET: self._datas.put(('burst', channel, data)) elif event == Message.Code.EVENT_RX_BROADCAST: self._datas.put(('broadcast', channel, data)) else: self._event_cond.acquire() self._events.append((channel, event, data)) self._event_cond.notify() self._event_cond.release() def _worker(self): self.ant.response_function = self._worker_response self.ant.channel_event_function = self._worker_event # TODO: check capabilities self.ant.start() def _main(self): while self._running: try: (data_type, channel, data) = self._datas.get(True, 1.0) self._datas.task_done() if data_type == 'broadcast': self.channels[channel].on_broadcast_data(data) elif data_type == 'burst': self.channels[channel].on_burst_data(data) else: _logger.warning("Unknown data type '%s': %r", data_type, data) except Queue.Empty as e: pass def start(self): self._main() def stop(self): if self._running: _logger.debug("Stoping ant.easy") self._running = False self.ant.stop() self._worker_thread.join()
Node
identifier_name
node.py
# Ant # # Copyright (c) 2012, Gustav Tiger <gustav@tiger.name> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. import collections import threading import logging import Queue from ant.base.ant import Ant from ant.base.message import Message from ant.easy.channel import Channel from ant.easy.filter import wait_for_event, wait_for_response, wait_for_special _logger = logging.getLogger("garmin.ant.easy.node") class Node(): def __init__(self): self._responses_cond = threading.Condition() self._responses = collections.deque() self._event_cond = threading.Condition() self._events = collections.deque() self._datas = Queue.Queue() self.channels = {} self.ant = Ant() self._running = True self._worker_thread = threading.Thread(target=self._worker, name="ant.easy") self._worker_thread.start() def new_channel(self, ctype): channel = Channel(0, self, self.ant) self.channels[0] = channel channel._assign(ctype, 0x00) return channel def request_message(self, messageId): _logger.debug("requesting message %#02x", messageId) self.ant.request_message(0, messageId) _logger.debug("done requesting message %#02x", messageId) return self.wait_for_special(messageId) def set_network_key(self, network, key):
def wait_for_event(self, ok_codes): return wait_for_event(ok_codes, self._events, self._event_cond) def wait_for_response(self, event_id): return wait_for_response(event_id, self._responses, self._responses_cond) def wait_for_special(self, event_id): return wait_for_special(event_id, self._responses, self._responses_cond) def _worker_response(self, channel, event, data): self._responses_cond.acquire() self._responses.append((channel, event, data)) self._responses_cond.notify() self._responses_cond.release() def _worker_event(self, channel, event, data): if event == Message.Code.EVENT_RX_BURST_PACKET: self._datas.put(('burst', channel, data)) elif event == Message.Code.EVENT_RX_BROADCAST: self._datas.put(('broadcast', channel, data)) else: self._event_cond.acquire() self._events.append((channel, event, data)) self._event_cond.notify() self._event_cond.release() def _worker(self): self.ant.response_function = self._worker_response self.ant.channel_event_function = self._worker_event # TODO: check capabilities self.ant.start() def _main(self): while self._running: try: (data_type, channel, data) = self._datas.get(True, 1.0) self._datas.task_done() if data_type == 'broadcast': self.channels[channel].on_broadcast_data(data) elif data_type == 'burst': self.channels[channel].on_burst_data(data) else: _logger.warning("Unknown data type '%s': %r", data_type, data) except Queue.Empty as e: pass def start(self): self._main() def stop(self): if self._running: _logger.debug("Stoping ant.easy") self._running = False self.ant.stop() self._worker_thread.join()
self.ant.set_network_key(network, key) return self.wait_for_response(Message.ID.SET_NETWORK_KEY)
identifier_body
selector-css2.js
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */ YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR)
} found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '3.9.0pr1', {"requires": ["selector-native"]});
{ token.combinator = Y.Selector.combinators[match[1]]; }
conditional_block
selector-css2.js
/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */ YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: {
}, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '3.9.0pr1', {"requires": ["selector-native"]});
'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; }
random_line_split
hkt_notes.rs
higher kinded types in rust struct List<A> { ... } /* note we could fully apply this or use trait Functor for List { ... } trait Functor for List<_> { ... } fn (&self<A> Functor<A> for List when we implement a normal trait we have a hidden type parameter if we look at Haskell for example, a simple show class looks like this class Show a show :: a -> String instance Show String show x = x trait Show { fn show(&self) -> String } // Here &self is &self is &String impl Show for String { fn
(&self) -> String { self.clone() } } If we move to an example like: // Could be named anything, just keeping with Haskell // convention, this represents a container that can be mapped ove // class Functor f map :: (a -> b) -> f a -> f b instance Functor [] where map f [] = [] map f (x:xs) = f x : map f xs trait Functor where Self<_> { ... } impl Functor for List
show
identifier_name
hkt_notes.rs
higher kinded types in rust struct List<A> { ... } /* note we could fully apply this or use trait Functor for List { ... } trait Functor for List<_> { ... } fn (&self<A> Functor<A> for List when we implement a normal trait we have a hidden type parameter if we look at Haskell for example, a simple show class looks like this class Show a show :: a -> String instance Show String show x = x trait Show { fn show(&self) -> String } // Here &self is &self is &String impl Show for String { fn show(&self) -> String { self.clone() } } If we move to an example like: // Could be named anything, just keeping with Haskell // convention, this represents a container that can be mapped ove //
map f (x:xs) = f x : map f xs trait Functor where Self<_> { ... } impl Functor for List
class Functor f map :: (a -> b) -> f a -> f b instance Functor [] where map f [] = []
random_line_split
ext.py
# -*- coding: utf-8 -*- from datetime import timedelta, datetime import asyncio import random from .api import every, once_at, JobSchedule, default_schedule_manager __all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday', 'every_thursday', 'every_friday', 'every_saturday', 'every_sunday', 'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday', 'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday', 'once_at_next_sunday', 'every_random_interval'] def every_random_interval(job, interval: timedelta, loop=None): """ executes the job randomly once in the specified interval. example: run a job every day at random time run a job every hour at random time :param job: a callable(co-routine function) which returns a co-routine or a future or an awaitable :param interval: the interval can also be given in the format of datetime.timedelta, then seconds, minutes, hours, days, weeks parameters are ignored. :param loop: io loop if the provided job is a custom future linked up with a different event loop. :return: schedule object, so it could be cancelled at will of the user by aschedule.cancel(schedule) """ if loop is None: loop = asyncio.get_event_loop() start = loop.time() def
(): count = 0 while True: rand = random.randrange(round(interval.total_seconds())) tmp = round(start + interval.total_seconds() * count + rand - loop.time()) yield tmp count += 1 schedule = JobSchedule(job, wait_time_gen(), loop=loop) # add it to default_schedule_manager, so that user can aschedule.cancel it default_schedule_manager.add_schedule(schedule) return schedule def every_day(job, loop=None): return every(job, timedelta=timedelta(days=1), loop=loop) def every_week(job, loop=None): return every(job, timedelta=timedelta(days=7), loop=loop) every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop) every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop) every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop) every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop) every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop) every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop) every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop) once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop) once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop) once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop) once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop) once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop) once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop) once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop) def _nearest_weekday(weekday): return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7) def _every_weekday(job, weekday, loop=None): return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop) def _once_at_weekday(job, weekday, loop=None): return once_at(job, _nearest_weekday(weekday), loop=loop)
wait_time_gen
identifier_name
ext.py
# -*- coding: utf-8 -*- from datetime import timedelta, datetime import asyncio import random from .api import every, once_at, JobSchedule, default_schedule_manager __all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday', 'every_thursday', 'every_friday', 'every_saturday', 'every_sunday', 'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday', 'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday', 'once_at_next_sunday', 'every_random_interval'] def every_random_interval(job, interval: timedelta, loop=None): """ executes the job randomly once in the specified interval. example: run a job every day at random time run a job every hour at random time :param job: a callable(co-routine function) which returns a co-routine or a future or an awaitable :param interval: the interval can also be given in the format of datetime.timedelta, then seconds, minutes, hours, days, weeks parameters are ignored. :param loop: io loop if the provided job is a custom future linked up with a different event loop. :return: schedule object, so it could be cancelled at will of the user by aschedule.cancel(schedule) """ if loop is None: loop = asyncio.get_event_loop() start = loop.time() def wait_time_gen():
schedule = JobSchedule(job, wait_time_gen(), loop=loop) # add it to default_schedule_manager, so that user can aschedule.cancel it default_schedule_manager.add_schedule(schedule) return schedule def every_day(job, loop=None): return every(job, timedelta=timedelta(days=1), loop=loop) def every_week(job, loop=None): return every(job, timedelta=timedelta(days=7), loop=loop) every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop) every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop) every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop) every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop) every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop) every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop) every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop) once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop) once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop) once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop) once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop) once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop) once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop) once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop) def _nearest_weekday(weekday): return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7) def _every_weekday(job, weekday, loop=None): return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop) def _once_at_weekday(job, weekday, loop=None): return once_at(job, _nearest_weekday(weekday), loop=loop)
count = 0 while True: rand = random.randrange(round(interval.total_seconds())) tmp = round(start + interval.total_seconds() * count + rand - loop.time()) yield tmp count += 1
identifier_body
ext.py
# -*- coding: utf-8 -*- from datetime import timedelta, datetime import asyncio import random from .api import every, once_at, JobSchedule, default_schedule_manager __all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday', 'every_thursday', 'every_friday', 'every_saturday', 'every_sunday', 'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday', 'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday', 'once_at_next_sunday', 'every_random_interval'] def every_random_interval(job, interval: timedelta, loop=None): """ executes the job randomly once in the specified interval. example: run a job every day at random time run a job every hour at random time :param job: a callable(co-routine function) which returns a co-routine or a future or an awaitable :param interval: the interval can also be given in the format of datetime.timedelta, then seconds, minutes, hours, days, weeks parameters are ignored. :param loop: io loop if the provided job is a custom future linked up with a different event loop. :return: schedule object, so it could be cancelled at will of the user by aschedule.cancel(schedule) """ if loop is None: loop = asyncio.get_event_loop() start = loop.time() def wait_time_gen(): count = 0 while True:
schedule = JobSchedule(job, wait_time_gen(), loop=loop) # add it to default_schedule_manager, so that user can aschedule.cancel it default_schedule_manager.add_schedule(schedule) return schedule def every_day(job, loop=None): return every(job, timedelta=timedelta(days=1), loop=loop) def every_week(job, loop=None): return every(job, timedelta=timedelta(days=7), loop=loop) every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop) every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop) every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop) every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop) every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop) every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop) every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop) once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop) once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop) once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop) once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop) once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop) once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop) once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop) def _nearest_weekday(weekday): return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7) def _every_weekday(job, weekday, loop=None): return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop) def _once_at_weekday(job, weekday, loop=None): return once_at(job, _nearest_weekday(weekday), loop=loop)
rand = random.randrange(round(interval.total_seconds())) tmp = round(start + interval.total_seconds() * count + rand - loop.time()) yield tmp count += 1
conditional_block
ext.py
# -*- coding: utf-8 -*- from datetime import timedelta, datetime import asyncio import random from .api import every, once_at, JobSchedule, default_schedule_manager __all__ = ['every_day', 'every_week', 'every_monday', 'every_tuesday', 'every_wednesday', 'every_thursday', 'every_friday', 'every_saturday', 'every_sunday', 'once_at_next_monday', 'once_at_next_tuesday', 'once_at_next_wednesday', 'once_at_next_thursday', 'once_at_next_friday', 'once_at_next_saturday', 'once_at_next_sunday', 'every_random_interval'] def every_random_interval(job, interval: timedelta, loop=None): """ executes the job randomly once in the specified interval. example: run a job every day at random time run a job every hour at random time :param job: a callable(co-routine function) which returns a co-routine or a future or an awaitable :param interval: the interval can also be given in the format of datetime.timedelta, then seconds, minutes, hours, days, weeks parameters are ignored. :param loop: io loop if the provided job is a custom future linked up with a different event loop. :return: schedule object, so it could be cancelled at will of the user by aschedule.cancel(schedule) """ if loop is None: loop = asyncio.get_event_loop() start = loop.time() def wait_time_gen(): count = 0 while True: rand = random.randrange(round(interval.total_seconds())) tmp = round(start + interval.total_seconds() * count + rand - loop.time()) yield tmp count += 1 schedule = JobSchedule(job, wait_time_gen(), loop=loop) # add it to default_schedule_manager, so that user can aschedule.cancel it default_schedule_manager.add_schedule(schedule) return schedule def every_day(job, loop=None): return every(job, timedelta=timedelta(days=1), loop=loop) def every_week(job, loop=None): return every(job, timedelta=timedelta(days=7), loop=loop)
every_monday = lambda job, loop=None: _every_weekday(job, 0, loop=loop) every_tuesday = lambda job, loop=None: _every_weekday(job, 1, loop=loop) every_wednesday = lambda job, loop=None: _every_weekday(job, 2, loop=loop) every_thursday = lambda job, loop=None: _every_weekday(job, 3, loop=loop) every_friday = lambda job, loop=None: _every_weekday(job, 4, loop=loop) every_saturday = lambda job, loop=None: _every_weekday(job, 5, loop=loop) every_sunday = lambda job, loop=None: _every_weekday(job, 6, loop=loop) once_at_next_monday = lambda job, loop=None: _once_at_weekday(job, 0, loop=loop) once_at_next_tuesday = lambda job, loop=None: _once_at_weekday(job, 1, loop=loop) once_at_next_wednesday = lambda job, loop=None: _once_at_weekday(job, 2, loop=loop) once_at_next_thursday = lambda job, loop=None: _once_at_weekday(job, 3, loop=loop) once_at_next_friday = lambda job, loop=None: _once_at_weekday(job, 4, loop=loop) once_at_next_saturday = lambda job, loop=None: _once_at_weekday(job, 5, loop=loop) once_at_next_sunday = lambda job, loop=None: _once_at_weekday(job, 6, loop=loop) def _nearest_weekday(weekday): return datetime.now() + timedelta(days=(weekday - datetime.now().weekday()) % 7) def _every_weekday(job, weekday, loop=None): return every(job, timedelta=timedelta(days=7), start_at=_nearest_weekday(weekday), loop=loop) def _once_at_weekday(job, weekday, loop=None): return once_at(job, _nearest_weekday(weekday), loop=loop)
random_line_split
lib.rs
//! Render to a window created by Glutin, using Glium's OpenGL functions #[macro_use] extern crate log; #[macro_use] extern crate glium; extern crate breeze_backend; use breeze_backend::{BackendAction, BackendResult, Renderer}; use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT}; use breeze_backend::viewport::Viewport; use glium::{DisplayBuild, Surface, Rect}; use glium::backend::glutin_backend::GlutinFacade; use glium::index::{NoIndices, PrimitiveType}; use glium::glutin::WindowBuilder; use glium::program::Program; use glium::texture::{ClientFormat, RawImage2d, SrgbTexture2d}; use glium::uniforms::MagnifySamplerFilter; use glium::vertex::VertexBuffer; use std::borrow::Cow; use std::error::Error; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); const VERTEX_SHADER_SRC: &'static str = r#" #version 140 in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main() { v_tex_coords = tex_coords; gl_Position = vec4(position, 0.0, 1.0); } "#; const FRAGMENT_SHADER_SRC: &'static str = r#" #version 140 in vec2 v_tex_coords; out vec4 color; uniform sampler2D tex; void main() { color = texture(tex, v_tex_coords); } "#; pub struct GliumRenderer { display: GlutinFacade, /// This vertex buffer will only ever store 4 vertices spanning the whole window vbuf: VertexBuffer<Vertex>, /// A simple shader that maps our texture onto the window program: Program, /// This texture is updated with the PPU's data every frame texture: SrgbTexture2d, } impl GliumRenderer { fn handle_events(&mut self) -> BackendResult<Vec<BackendAction>> { use glium::glutin::Event::*; for ev in self.display.poll_events() { match ev { Closed => { info!("quit event -> exiting"); return Ok(vec![BackendAction::Exit]); } Resized(w, h) =>
_ => {} } } Ok(vec![]) } } fn resize(vbuf: &mut VertexBuffer<Vertex>, win_w: u32, win_h: u32) { let Viewport { x, y, w, h } = Viewport::for_window_size(win_w, win_h); let (win_w, win_h) = (win_w as f32, win_h as f32); let (x, y, w, h) = (x as f32 / win_w, y as f32 / win_h, w as f32 / win_w, h as f32 / win_h); // Since I can't be bothered to put in a translation matrix, we have to translate the pixel // coords to OpenGL's [-1, 1] system. let vx = (x - 0.5) * 2.0; let vy = (y - 0.5) * 2.0; let rect = make_rect(vx, vy, w * 2.0, h * 2.0); vbuf.write(&rect); } /// Build 4 Vertices spanning up a rectangle. Bottom-Left corner = (-1, -1). fn make_rect(x: f32, y: f32, w: f32, h: f32) -> [Vertex; 4] { // FIXME Use a matrix instead of rebuilding the geometry on every resize [ Vertex { position: [x, y + h], tex_coords: [0.0, 0.0] }, Vertex { position: [x + w, y + h], tex_coords: [1.0, 0.0] }, Vertex { position: [x, y], tex_coords: [0.0, 1.0] }, Vertex { position: [x + w, y], tex_coords: [1.0, 1.0] }, ] } impl Renderer for GliumRenderer { fn create() -> Result<Self, Box<Error>> { let display = try!(WindowBuilder::new() .with_dimensions(SCREEN_WIDTH * 3, SCREEN_HEIGHT * 3) .with_title("breeze".to_owned()) .build_glium()); let mut vbuf = try!(VertexBuffer::empty_dynamic(&display, 4)); resize(&mut vbuf, SCREEN_WIDTH * 3, SCREEN_HEIGHT * 3); Ok(GliumRenderer { vbuf: vbuf, program: try!( Program::from_source(&display, VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC, None)), texture: try!(SrgbTexture2d::empty(&display, SCREEN_WIDTH, SCREEN_HEIGHT)), display: display, }) } fn render(&mut self, frame_data: &[u8]) -> BackendResult<Vec<BackendAction>> { // upload new texture data self.texture.write(Rect { left: 0, bottom: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT, }, RawImage2d { data: Cow::Borrowed(frame_data), width: SCREEN_WIDTH, height: SCREEN_HEIGHT, format: ClientFormat::U8U8U8, }); let mut target = self.display.draw(); target.clear_color_srgb(0.0, 0.0, 0.0, 0.0); target.draw( &self.vbuf, &NoIndices(PrimitiveType::TriangleStrip), &self.program, &uniform! { tex: self.texture.sampled() .magnify_filter(MagnifySamplerFilter::Nearest), }, &Default::default()).unwrap(); target.finish().unwrap(); self.handle_events() } fn set_rom_title(&mut self, title: &str) { if let Some(win_ref) = self.display.get_window() { win_ref.set_title(title); } } }
{ resize(&mut self.vbuf, w, h); }
conditional_block
lib.rs
//! Render to a window created by Glutin, using Glium's OpenGL functions #[macro_use] extern crate log; #[macro_use] extern crate glium; extern crate breeze_backend; use breeze_backend::{BackendAction, BackendResult, Renderer}; use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT}; use breeze_backend::viewport::Viewport; use glium::{DisplayBuild, Surface, Rect}; use glium::backend::glutin_backend::GlutinFacade; use glium::index::{NoIndices, PrimitiveType}; use glium::glutin::WindowBuilder; use glium::program::Program; use glium::texture::{ClientFormat, RawImage2d, SrgbTexture2d}; use glium::uniforms::MagnifySamplerFilter; use glium::vertex::VertexBuffer; use std::borrow::Cow; use std::error::Error; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); const VERTEX_SHADER_SRC: &'static str = r#" #version 140 in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main() { v_tex_coords = tex_coords; gl_Position = vec4(position, 0.0, 1.0); } "#; const FRAGMENT_SHADER_SRC: &'static str = r#" #version 140 in vec2 v_tex_coords; out vec4 color; uniform sampler2D tex; void main() { color = texture(tex, v_tex_coords); } "#; pub struct GliumRenderer { display: GlutinFacade, /// This vertex buffer will only ever store 4 vertices spanning the whole window vbuf: VertexBuffer<Vertex>, /// A simple shader that maps our texture onto the window program: Program, /// This texture is updated with the PPU's data every frame texture: SrgbTexture2d, } impl GliumRenderer { fn handle_events(&mut self) -> BackendResult<Vec<BackendAction>> { use glium::glutin::Event::*; for ev in self.display.poll_events() { match ev { Closed => { info!("quit event -> exiting"); return Ok(vec![BackendAction::Exit]); } Resized(w, h) => { resize(&mut self.vbuf, w, h); } _ => {} } } Ok(vec![]) } } fn resize(vbuf: &mut VertexBuffer<Vertex>, win_w: u32, win_h: u32) { let Viewport { x, y, w, h } = Viewport::for_window_size(win_w, win_h); let (win_w, win_h) = (win_w as f32, win_h as f32); let (x, y, w, h) = (x as f32 / win_w, y as f32 / win_h, w as f32 / win_w, h as f32 / win_h); // Since I can't be bothered to put in a translation matrix, we have to translate the pixel // coords to OpenGL's [-1, 1] system. let vx = (x - 0.5) * 2.0; let vy = (y - 0.5) * 2.0; let rect = make_rect(vx, vy, w * 2.0, h * 2.0); vbuf.write(&rect); } /// Build 4 Vertices spanning up a rectangle. Bottom-Left corner = (-1, -1). fn make_rect(x: f32, y: f32, w: f32, h: f32) -> [Vertex; 4] { // FIXME Use a matrix instead of rebuilding the geometry on every resize [ Vertex { position: [x, y + h], tex_coords: [0.0, 0.0] }, Vertex { position: [x + w, y + h], tex_coords: [1.0, 0.0] }, Vertex { position: [x, y], tex_coords: [0.0, 1.0] }, Vertex { position: [x + w, y], tex_coords: [1.0, 1.0] }, ] } impl Renderer for GliumRenderer { fn create() -> Result<Self, Box<Error>> { let display = try!(WindowBuilder::new() .with_dimensions(SCREEN_WIDTH * 3, SCREEN_HEIGHT * 3) .with_title("breeze".to_owned()) .build_glium()); let mut vbuf = try!(VertexBuffer::empty_dynamic(&display, 4)); resize(&mut vbuf, SCREEN_WIDTH * 3, SCREEN_HEIGHT * 3); Ok(GliumRenderer { vbuf: vbuf, program: try!( Program::from_source(&display, VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC, None)), texture: try!(SrgbTexture2d::empty(&display, SCREEN_WIDTH, SCREEN_HEIGHT)), display: display, }) } fn render(&mut self, frame_data: &[u8]) -> BackendResult<Vec<BackendAction>> { // upload new texture data self.texture.write(Rect { left: 0, bottom: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT, }, RawImage2d {
format: ClientFormat::U8U8U8, }); let mut target = self.display.draw(); target.clear_color_srgb(0.0, 0.0, 0.0, 0.0); target.draw( &self.vbuf, &NoIndices(PrimitiveType::TriangleStrip), &self.program, &uniform! { tex: self.texture.sampled() .magnify_filter(MagnifySamplerFilter::Nearest), }, &Default::default()).unwrap(); target.finish().unwrap(); self.handle_events() } fn set_rom_title(&mut self, title: &str) { if let Some(win_ref) = self.display.get_window() { win_ref.set_title(title); } } }
data: Cow::Borrowed(frame_data), width: SCREEN_WIDTH, height: SCREEN_HEIGHT,
random_line_split
lib.rs
//! Render to a window created by Glutin, using Glium's OpenGL functions #[macro_use] extern crate log; #[macro_use] extern crate glium; extern crate breeze_backend; use breeze_backend::{BackendAction, BackendResult, Renderer}; use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT}; use breeze_backend::viewport::Viewport; use glium::{DisplayBuild, Surface, Rect}; use glium::backend::glutin_backend::GlutinFacade; use glium::index::{NoIndices, PrimitiveType}; use glium::glutin::WindowBuilder; use glium::program::Program; use glium::texture::{ClientFormat, RawImage2d, SrgbTexture2d}; use glium::uniforms::MagnifySamplerFilter; use glium::vertex::VertexBuffer; use std::borrow::Cow; use std::error::Error; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); const VERTEX_SHADER_SRC: &'static str = r#" #version 140 in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main() { v_tex_coords = tex_coords; gl_Position = vec4(position, 0.0, 1.0); } "#; const FRAGMENT_SHADER_SRC: &'static str = r#" #version 140 in vec2 v_tex_coords; out vec4 color; uniform sampler2D tex; void main() { color = texture(tex, v_tex_coords); } "#; pub struct GliumRenderer { display: GlutinFacade, /// This vertex buffer will only ever store 4 vertices spanning the whole window vbuf: VertexBuffer<Vertex>, /// A simple shader that maps our texture onto the window program: Program, /// This texture is updated with the PPU's data every frame texture: SrgbTexture2d, } impl GliumRenderer { fn handle_events(&mut self) -> BackendResult<Vec<BackendAction>> { use glium::glutin::Event::*; for ev in self.display.poll_events() { match ev { Closed => { info!("quit event -> exiting"); return Ok(vec![BackendAction::Exit]); } Resized(w, h) => { resize(&mut self.vbuf, w, h); } _ => {} } } Ok(vec![]) } } fn resize(vbuf: &mut VertexBuffer<Vertex>, win_w: u32, win_h: u32) { let Viewport { x, y, w, h } = Viewport::for_window_size(win_w, win_h); let (win_w, win_h) = (win_w as f32, win_h as f32); let (x, y, w, h) = (x as f32 / win_w, y as f32 / win_h, w as f32 / win_w, h as f32 / win_h); // Since I can't be bothered to put in a translation matrix, we have to translate the pixel // coords to OpenGL's [-1, 1] system. let vx = (x - 0.5) * 2.0; let vy = (y - 0.5) * 2.0; let rect = make_rect(vx, vy, w * 2.0, h * 2.0); vbuf.write(&rect); } /// Build 4 Vertices spanning up a rectangle. Bottom-Left corner = (-1, -1). fn make_rect(x: f32, y: f32, w: f32, h: f32) -> [Vertex; 4] { // FIXME Use a matrix instead of rebuilding the geometry on every resize [ Vertex { position: [x, y + h], tex_coords: [0.0, 0.0] }, Vertex { position: [x + w, y + h], tex_coords: [1.0, 0.0] }, Vertex { position: [x, y], tex_coords: [0.0, 1.0] }, Vertex { position: [x + w, y], tex_coords: [1.0, 1.0] }, ] } impl Renderer for GliumRenderer { fn create() -> Result<Self, Box<Error>> { let display = try!(WindowBuilder::new() .with_dimensions(SCREEN_WIDTH * 3, SCREEN_HEIGHT * 3) .with_title("breeze".to_owned()) .build_glium()); let mut vbuf = try!(VertexBuffer::empty_dynamic(&display, 4)); resize(&mut vbuf, SCREEN_WIDTH * 3, SCREEN_HEIGHT * 3); Ok(GliumRenderer { vbuf: vbuf, program: try!( Program::from_source(&display, VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC, None)), texture: try!(SrgbTexture2d::empty(&display, SCREEN_WIDTH, SCREEN_HEIGHT)), display: display, }) } fn
(&mut self, frame_data: &[u8]) -> BackendResult<Vec<BackendAction>> { // upload new texture data self.texture.write(Rect { left: 0, bottom: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT, }, RawImage2d { data: Cow::Borrowed(frame_data), width: SCREEN_WIDTH, height: SCREEN_HEIGHT, format: ClientFormat::U8U8U8, }); let mut target = self.display.draw(); target.clear_color_srgb(0.0, 0.0, 0.0, 0.0); target.draw( &self.vbuf, &NoIndices(PrimitiveType::TriangleStrip), &self.program, &uniform! { tex: self.texture.sampled() .magnify_filter(MagnifySamplerFilter::Nearest), }, &Default::default()).unwrap(); target.finish().unwrap(); self.handle_events() } fn set_rom_title(&mut self, title: &str) { if let Some(win_ref) = self.display.get_window() { win_ref.set_title(title); } } }
render
identifier_name
user.js
import nextConnect from 'next-connect' import auth from '../../middleware/auth' import { deleteUser, updateUserByUsername } from '../../lib/db' const handler = nextConnect() handler .use(auth) .get((req, res) => { // You do not generally want to return the whole user object // because it may contain sensitive field such as !!password!! Only return what needed // const { name, username, favoriteColor } = req.user // res.json({ user: { name, username, favoriteColor } }) res.json({ user: req.user }) }) .use((req, res, next) => { // handlers after this (PUT, DELETE) all require an authenticated user // This middleware to check if user is authenticated before continuing if (!req.user) { res.status(401).send('unauthenticated') } else { next() } }) .put((req, res) => { const { name } = req.body const user = updateUserByUsername(req, req.user.username, { name }) res.json({ user }) }) .delete((req, res) => { deleteUser(req)
req.logOut() res.status(204).end() }) export default handler
random_line_split
user.js
import nextConnect from 'next-connect' import auth from '../../middleware/auth' import { deleteUser, updateUserByUsername } from '../../lib/db' const handler = nextConnect() handler .use(auth) .get((req, res) => { // You do not generally want to return the whole user object // because it may contain sensitive field such as !!password!! Only return what needed // const { name, username, favoriteColor } = req.user // res.json({ user: { name, username, favoriteColor } }) res.json({ user: req.user }) }) .use((req, res, next) => { // handlers after this (PUT, DELETE) all require an authenticated user // This middleware to check if user is authenticated before continuing if (!req.user) { res.status(401).send('unauthenticated') } else
}) .put((req, res) => { const { name } = req.body const user = updateUserByUsername(req, req.user.username, { name }) res.json({ user }) }) .delete((req, res) => { deleteUser(req) req.logOut() res.status(204).end() }) export default handler
{ next() }
conditional_block
schools_with_description_2020.py
import logging from datetime import datetime import math import numpy as np import pandas as pd from flask_sqlalchemy import SQLAlchemy from ..models import SchoolWithDescription2020 from ..utilities import init_flask, time_delta, chunks, ItmToWGS84 school_fields = { "school_id": "סמל_מוסד", "school_name": "שם_מוסד", "municipality_name": "שם_רשות", "yishuv_name": "שם_ישוב", "institution_type": "סוג_מוסד", "lowest_grade": "משכבה", "highest_grade": "עד_שכבה", "location_accuracy": "רמת_דיוק_מיקום", "x": "X", "y": "Y", } app = init_flask() db = SQLAlchemy(app) coordinates_converter = ItmToWGS84() def get_numeric_value(value, func): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return func(value) if value and not np.isnan(value) else None def get_str_value(value): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return value if value and value not in ["nan", "Nan", "NaN", "NAN"] else None def get_schools_with_description(schools_description_filepath, schools_coordinates_filepath): logging.info("\tReading schools description data from '%s'..." % schools_description_filepath) df_schools = pd.read_excel(schools_description_filepath) logging.info("\tReading schools coordinates data from '%s'..." % schools_coordinates_filepath) df_coordinates = pd.read_excel(schools_coordinates_filepath) schools = [] # get school_id df_schools = df_schools.drop_duplicates(school_fields["school_id"]) # sort by school_id df_schools = df_schools.sort_values(school_fields["school_id"], ascending=True) all_schools_tuples = [] for _, school in df_schools.iterrows(): school_id = get_numeric_value(school[school_fields["school_id"]], int) school_name = get_str_value(school[school_fields["school_name"]]).strip('"') if school_id in list(df_coordinates[school_fields["school_id"]].values): x_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["x"] ].values[0] y_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["y"] ].values[0] location_accuracy = get_str_value( df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["location_accuracy"], ].values[0] ) else: x_coord = None y_coord = None location_accuracy = None if x_coord and not math.isnan(x_coord) and y_coord and not math.isnan(y_coord): longitude, latitude = coordinates_converter.convert(x_coord, y_coord) else: longitude, latitude = ( None, None, ) # otherwise yield will produce: UnboundLocalError: local variable referenced before assignment # Don't insert duplicates of 'school_name','x', 'y' school_tuple = (school_name, x_coord, y_coord) if school_tuple in all_schools_tuples: continue else: all_schools_tuples.append(school_tuple) school = { "school_id": get_numeric_value(school[school_fields["school_id"]], int), "school_name": school_name, "municipality_name": get_str_value(school[school_fields["municipality_name"]]), "yishuv_name": get_str_value(school[school_fields["yishuv_name"]]), "institution_type": get_str_value(school[school_fields["institution_type"]]), "lowest_grade": get_str_value(school[school_fields["lowest_grade"]]), "highest_grade": get_str_value(school[school_fields["highest_grade"]]), "location_accuracy": location_accuracy, "longitude": longitude, "latitude": latitude, "x": x_coord, "y": y_coord, } if school["institution_type"] in [ "בית ספר", "תלמוד תורה", "ישיבה קטנה", 'בי"ס תורני', "ישיבה תיכונית", 'בי"ס חקלאי', 'בי"ס רפואי', 'בי"ס כנסייתי', "אולפנה", 'בי"ס אקסטרני', 'בי"ס קיבוצי', "תלמוד תורה ליד מעיין חינוך התורני", 'בי"ס מושבי', ]: schools.append(school) return schools def truncate_schools_with_description(): curr_table = "schools_with_description" sql_truncate = "TRUNCATE TABLE " + curr_table db.session.execute(sql_truncate) db.session.commit() logging.info("Truncated table " + curr_table) def import_to_datastore(schools_description_filepath, schools_coordinates_filepath, batch_size): try: assert batch_size > 0 started = datetime.now() schools = get
iption( schools_description_filepath, schools_coordinates_filepath ) truncate_schools_with_description() new_items = 0 logging.info("inserting " + str(len(schools)) + " new schools") for schools_chunk in chunks(schools, batch_size): db.session.bulk_insert_mappings(SchoolWithDescription2020, schools_chunk) db.session.commit() new_items += len(schools) logging.info(f"\t{new_items} items in {time_delta(started)}") return new_items except Exception as exception: error = f"Schools import succeeded partially with {new_items} schools. Got exception : {exception}" raise Exception(error) def parse(schools_description_filepath, schools_coordinates_filepath, batch_size): started = datetime.now() total = import_to_datastore( schools_description_filepath=schools_description_filepath, schools_coordinates_filepath=schools_coordinates_filepath, batch_size=batch_size, ) db.session.execute( "UPDATE schools_with_description SET geom = ST_SetSRID(ST_MakePoint(longitude,latitude),4326)\ WHERE geom IS NULL;" ) logging.info("Total: {0} schools in {1}".format(total, time_delta(started)))
_schools_with_descr
identifier_name
schools_with_description_2020.py
import logging from datetime import datetime import math import numpy as np import pandas as pd from flask_sqlalchemy import SQLAlchemy from ..models import SchoolWithDescription2020 from ..utilities import init_flask, time_delta, chunks, ItmToWGS84 school_fields = { "school_id": "סמל_מוסד", "school_name": "שם_מוסד", "municipality_name": "שם_רשות", "yishuv_name": "שם_ישוב", "institution_type": "סוג_מוסד", "lowest_grade": "משכבה", "highest_grade": "עד_שכבה", "location_accuracy": "רמת_דיוק_מיקום", "x": "X", "y": "Y", } app = init_flask() db = SQLAlchemy(app) coordinates_converter = ItmToWGS84() def get_numeric_value(value, func): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return func(value) if value and not np.isnan(value) else None def get_str_value(value): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return value if value and value not in ["nan", "Nan", "NaN", "NAN"] else None def get_schools_with_description(schools_description_filepath, schools_coordinates_filepath): logging.info("\tReading schools description data from '%s'..." % schools_description_filepath) df_schools = pd.read_excel(schools_description_filepath) logging.info("\tReading schools coordinates data from '%s'..." % schools_coordinates_filepath) df_coordinates = pd.read_excel(schools_coordinates_filepath) schools = [] # get school_id df_schools = df_schools.drop_duplicates(school_fields["school_id"]) # sort by school_id df_schools = df_schools.sort_values(school_fields["school_id"], ascending=True) all_schools_tuples = [] for _, school in df_schools.iterrows(): school_id = get_numeric_value(school[school_fields["school_id"]], int) school_name = get_str_value(school[school_fields["school_name"]]).strip('"') if school_id in list(df_coordinates[school_fields["school_id"]].values): x_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["x"] ].values[0] y_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["y"] ].values[0] location_accuracy = get_str_value( df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["location_accuracy"], ].values[0] ) else: x_coord = None y_coord = None location_accuracy = None if x_coord and not math.isnan(x_coord) and y_coord and not math.isnan(y_coord): longitude, latitude = coordinates_converter.convert(x_coord, y_coord) else: longitude, latitude = ( None, None, ) # otherwise yield will produce: UnboundLocalError: local variable referenced before assignment # Don't insert duplicates of 'school_name','x', 'y' school_tuple = (school_name, x_coord, y_coord) if school_tuple in all_schools_tuples: continue else: all_schools_tuples.a
hool_tuple) school = { "school_id": get_numeric_value(school[school_fields["school_id"]], int), "school_name": school_name, "municipality_name": get_str_value(school[school_fields["municipality_name"]]), "yishuv_name": get_str_value(school[school_fields["yishuv_name"]]), "institution_type": get_str_value(school[school_fields["institution_type"]]), "lowest_grade": get_str_value(school[school_fields["lowest_grade"]]), "highest_grade": get_str_value(school[school_fields["highest_grade"]]), "location_accuracy": location_accuracy, "longitude": longitude, "latitude": latitude, "x": x_coord, "y": y_coord, } if school["institution_type"] in [ "בית ספר", "תלמוד תורה", "ישיבה קטנה", 'בי"ס תורני', "ישיבה תיכונית", 'בי"ס חקלאי', 'בי"ס רפואי', 'בי"ס כנסייתי', "אולפנה", 'בי"ס אקסטרני', 'בי"ס קיבוצי', "תלמוד תורה ליד מעיין חינוך התורני", 'בי"ס מושבי', ]: schools.append(school) return schools def truncate_schools_with_description(): curr_table = "schools_with_description" sql_truncate = "TRUNCATE TABLE " + curr_table db.session.execute(sql_truncate) db.session.commit() logging.info("Truncated table " + curr_table) def import_to_datastore(schools_description_filepath, schools_coordinates_filepath, batch_size): try: assert batch_size > 0 started = datetime.now() schools = get_schools_with_description( schools_description_filepath, schools_coordinates_filepath ) truncate_schools_with_description() new_items = 0 logging.info("inserting " + str(len(schools)) + " new schools") for schools_chunk in chunks(schools, batch_size): db.session.bulk_insert_mappings(SchoolWithDescription2020, schools_chunk) db.session.commit() new_items += len(schools) logging.info(f"\t{new_items} items in {time_delta(started)}") return new_items except Exception as exception: error = f"Schools import succeeded partially with {new_items} schools. Got exception : {exception}" raise Exception(error) def parse(schools_description_filepath, schools_coordinates_filepath, batch_size): started = datetime.now() total = import_to_datastore( schools_description_filepath=schools_description_filepath, schools_coordinates_filepath=schools_coordinates_filepath, batch_size=batch_size, ) db.session.execute( "UPDATE schools_with_description SET geom = ST_SetSRID(ST_MakePoint(longitude,latitude),4326)\ WHERE geom IS NULL;" ) logging.info("Total: {0} schools in {1}".format(total, time_delta(started)))
ppend(sc
conditional_block
schools_with_description_2020.py
import logging from datetime import datetime import math import numpy as np import pandas as pd from flask_sqlalchemy import SQLAlchemy from ..models import SchoolWithDescription2020 from ..utilities import init_flask, time_delta, chunks, ItmToWGS84 school_fields = { "school_id": "סמל_מוסד", "school_name": "שם_מוסד", "municipality_name": "שם_רשות", "yishuv_name": "שם_ישוב", "institution_type": "סוג_מוסד", "lowest_grade": "משכבה", "highest_grade": "עד_שכבה", "location_accuracy": "רמת_דיוק_מיקום", "x": "X", "y": "Y", } app = init_flask() db = SQLAlchemy(app) coordinates_converter = ItmToWGS84() def get_numeric_value(value, func): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return func(value) if value and not np.isnan(value) else None def get_str_value(value): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return value if value and value not in ["nan", "Nan", "NaN", "NAN"] else None def get_schools_with_description(schools_description_filepath, schools_coordinates_filepath): logging.info("\tReading schools description data from '
ion.commit() logging.info("Truncated table " + curr_table) def import_to_datastore(schools_description_filepath, schools_coordinates_filepath, batch_size): try: assert batch_size > 0 started = datetime.now() schools = get_schools_with_description( schools_description_filepath, schools_coordinates_filepath ) truncate_schools_with_description() new_items = 0 logging.info("inserting " + str(len(schools)) + " new schools") for schools_chunk in chunks(schools, batch_size): db.session.bulk_insert_mappings(SchoolWithDescription2020, schools_chunk) db.session.commit() new_items += len(schools) logging.info(f"\t{new_items} items in {time_delta(started)}") return new_items except Exception as exception: error = f"Schools import succeeded partially with {new_items} schools. Got exception : {exception}" raise Exception(error) def parse(schools_description_filepath, schools_coordinates_filepath, batch_size): started = datetime.now() total = import_to_datastore( schools_description_filepath=schools_description_filepath, schools_coordinates_filepath=schools_coordinates_filepath, batch_size=batch_size, ) db.session.execute( "UPDATE schools_with_description SET geom = ST_SetSRID(ST_MakePoint(longitude,latitude),4326)\ WHERE geom IS NULL;" ) logging.info("Total: {0} schools in {1}".format(total, time_delta(started)))
%s'..." % schools_description_filepath) df_schools = pd.read_excel(schools_description_filepath) logging.info("\tReading schools coordinates data from '%s'..." % schools_coordinates_filepath) df_coordinates = pd.read_excel(schools_coordinates_filepath) schools = [] # get school_id df_schools = df_schools.drop_duplicates(school_fields["school_id"]) # sort by school_id df_schools = df_schools.sort_values(school_fields["school_id"], ascending=True) all_schools_tuples = [] for _, school in df_schools.iterrows(): school_id = get_numeric_value(school[school_fields["school_id"]], int) school_name = get_str_value(school[school_fields["school_name"]]).strip('"') if school_id in list(df_coordinates[school_fields["school_id"]].values): x_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["x"] ].values[0] y_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["y"] ].values[0] location_accuracy = get_str_value( df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["location_accuracy"], ].values[0] ) else: x_coord = None y_coord = None location_accuracy = None if x_coord and not math.isnan(x_coord) and y_coord and not math.isnan(y_coord): longitude, latitude = coordinates_converter.convert(x_coord, y_coord) else: longitude, latitude = ( None, None, ) # otherwise yield will produce: UnboundLocalError: local variable referenced before assignment # Don't insert duplicates of 'school_name','x', 'y' school_tuple = (school_name, x_coord, y_coord) if school_tuple in all_schools_tuples: continue else: all_schools_tuples.append(school_tuple) school = { "school_id": get_numeric_value(school[school_fields["school_id"]], int), "school_name": school_name, "municipality_name": get_str_value(school[school_fields["municipality_name"]]), "yishuv_name": get_str_value(school[school_fields["yishuv_name"]]), "institution_type": get_str_value(school[school_fields["institution_type"]]), "lowest_grade": get_str_value(school[school_fields["lowest_grade"]]), "highest_grade": get_str_value(school[school_fields["highest_grade"]]), "location_accuracy": location_accuracy, "longitude": longitude, "latitude": latitude, "x": x_coord, "y": y_coord, } if school["institution_type"] in [ "בית ספר", "תלמוד תורה", "ישיבה קטנה", 'בי"ס תורני', "ישיבה תיכונית", 'בי"ס חקלאי', 'בי"ס רפואי', 'בי"ס כנסייתי', "אולפנה", 'בי"ס אקסטרני', 'בי"ס קיבוצי', "תלמוד תורה ליד מעיין חינוך התורני", 'בי"ס מושבי', ]: schools.append(school) return schools def truncate_schools_with_description(): curr_table = "schools_with_description" sql_truncate = "TRUNCATE TABLE " + curr_table db.session.execute(sql_truncate) db.sess
identifier_body
schools_with_description_2020.py
import logging from datetime import datetime import math import numpy as np import pandas as pd from flask_sqlalchemy import SQLAlchemy from ..models import SchoolWithDescription2020 from ..utilities import init_flask, time_delta, chunks, ItmToWGS84 school_fields = { "school_id": "סמל_מוסד", "school_name": "שם_מוסד", "municipality_name": "שם_רשות", "yishuv_name": "שם_ישוב", "institution_type": "סוג_מוסד", "lowest_grade": "משכבה", "highest_grade": "עד_שכבה", "location_accuracy": "רמת_דיוק_מיקום", "x": "X", "y": "Y", } app = init_flask() db = SQLAlchemy(app) coordinates_converter = ItmToWGS84() def get_numeric_value(value, func): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return func(value) if value and not np.isnan(value) else None def get_str_value(value): """ :returns: value if parameter value exists OR None if the parameter value does not exist """ return value if value and value not in ["nan", "Nan", "NaN", "NAN"] else None def get_schools_with_description(schools_description_filepath, schools_coordinates_filepath): logging.info("\tReading schools description data from '%s'..." % schools_description_filepath) df_schools = pd.read_excel(schools_description_filepath) logging.info("\tReading schools coordinates data from '%s'..." % schools_coordinates_filepath) df_coordinates = pd.read_excel(schools_coordinates_filepath) schools = [] # get school_id
df_schools = df_schools.drop_duplicates(school_fields["school_id"]) # sort by school_id df_schools = df_schools.sort_values(school_fields["school_id"], ascending=True) all_schools_tuples = [] for _, school in df_schools.iterrows(): school_id = get_numeric_value(school[school_fields["school_id"]], int) school_name = get_str_value(school[school_fields["school_name"]]).strip('"') if school_id in list(df_coordinates[school_fields["school_id"]].values): x_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["x"] ].values[0] y_coord = df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["y"] ].values[0] location_accuracy = get_str_value( df_coordinates.loc[ df_coordinates[school_fields["school_id"]] == school_id, school_fields["location_accuracy"], ].values[0] ) else: x_coord = None y_coord = None location_accuracy = None if x_coord and not math.isnan(x_coord) and y_coord and not math.isnan(y_coord): longitude, latitude = coordinates_converter.convert(x_coord, y_coord) else: longitude, latitude = ( None, None, ) # otherwise yield will produce: UnboundLocalError: local variable referenced before assignment # Don't insert duplicates of 'school_name','x', 'y' school_tuple = (school_name, x_coord, y_coord) if school_tuple in all_schools_tuples: continue else: all_schools_tuples.append(school_tuple) school = { "school_id": get_numeric_value(school[school_fields["school_id"]], int), "school_name": school_name, "municipality_name": get_str_value(school[school_fields["municipality_name"]]), "yishuv_name": get_str_value(school[school_fields["yishuv_name"]]), "institution_type": get_str_value(school[school_fields["institution_type"]]), "lowest_grade": get_str_value(school[school_fields["lowest_grade"]]), "highest_grade": get_str_value(school[school_fields["highest_grade"]]), "location_accuracy": location_accuracy, "longitude": longitude, "latitude": latitude, "x": x_coord, "y": y_coord, } if school["institution_type"] in [ "בית ספר", "תלמוד תורה", "ישיבה קטנה", 'בי"ס תורני', "ישיבה תיכונית", 'בי"ס חקלאי', 'בי"ס רפואי', 'בי"ס כנסייתי', "אולפנה", 'בי"ס אקסטרני', 'בי"ס קיבוצי', "תלמוד תורה ליד מעיין חינוך התורני", 'בי"ס מושבי', ]: schools.append(school) return schools def truncate_schools_with_description(): curr_table = "schools_with_description" sql_truncate = "TRUNCATE TABLE " + curr_table db.session.execute(sql_truncate) db.session.commit() logging.info("Truncated table " + curr_table) def import_to_datastore(schools_description_filepath, schools_coordinates_filepath, batch_size): try: assert batch_size > 0 started = datetime.now() schools = get_schools_with_description( schools_description_filepath, schools_coordinates_filepath ) truncate_schools_with_description() new_items = 0 logging.info("inserting " + str(len(schools)) + " new schools") for schools_chunk in chunks(schools, batch_size): db.session.bulk_insert_mappings(SchoolWithDescription2020, schools_chunk) db.session.commit() new_items += len(schools) logging.info(f"\t{new_items} items in {time_delta(started)}") return new_items except Exception as exception: error = f"Schools import succeeded partially with {new_items} schools. Got exception : {exception}" raise Exception(error) def parse(schools_description_filepath, schools_coordinates_filepath, batch_size): started = datetime.now() total = import_to_datastore( schools_description_filepath=schools_description_filepath, schools_coordinates_filepath=schools_coordinates_filepath, batch_size=batch_size, ) db.session.execute( "UPDATE schools_with_description SET geom = ST_SetSRID(ST_MakePoint(longitude,latitude),4326)\ WHERE geom IS NULL;" ) logging.info("Total: {0} schools in {1}".format(total, time_delta(started)))
random_line_split
elastic.js
/* * angular-elastic v2.4.2 * (c) 2014 Monospaced http://monospaced.com * License: MIT */ angular.module('monospaced.elastic', []) .constant('msdElasticConfig', { append: '' }) .directive('msdElastic', [ '$timeout', '$window', 'msdElasticConfig', function($timeout, $window, config) { 'use strict'; return { require: 'ngModel', restrict: 'A, C', link: function(scope, element, attrs, ngModel) { // cache a reference to the DOM element var ta = element[0], $ta = element; // ensure the element is a textarea, and browser is capable if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle) { return; } // set these properties before measuring dimensions $ta.css({ 'overflow': 'hidden', 'overflow-y': 'hidden', 'word-wrap': 'break-word' }); // force text reflow var text = ta.value; ta.value = ''; ta.value = text; var append = attrs.msdElastic ? attrs.msdElastic.replace(/\\n/g, '\n') : config.append, $win = angular.element($window), mirrorInitStyle = 'position: absolute; top: -999px; right: auto; bottom: auto;' + 'left: 0; overflow: hidden; -webkit-box-sizing: content-box;' + '-moz-box-sizing: content-box; box-sizing: content-box;' + 'min-height: 0 !important; height: 0 !important; padding: 0;' + 'word-wrap: break-word; border: 0;', $mirror = angular.element('<textarea tabindex="-1" ' + 'style="' + mirrorInitStyle + '"/>').data('elastic', true), mirror = $mirror[0], taStyle = getComputedStyle(ta), resize = taStyle.getPropertyValue('resize'), borderBox = taStyle.getPropertyValue('box-sizing') === 'border-box' || taStyle.getPropertyValue('-moz-box-sizing') === 'border-box' || taStyle.getPropertyValue('-webkit-box-sizing') === 'border-box', boxOuter = !borderBox ? {width: 0, height: 0} : { width: parseInt(taStyle.getPropertyValue('border-right-width'), 10) + parseInt(taStyle.getPropertyValue('padding-right'), 10) + parseInt(taStyle.getPropertyValue('padding-left'), 10) + parseInt(taStyle.getPropertyValue('border-left-width'), 10), height: parseInt(taStyle.getPropertyValue('border-top-width'), 10) + parseInt(taStyle.getPropertyValue('padding-top'), 10) + parseInt(taStyle.getPropertyValue('padding-bottom'), 10) + parseInt(taStyle.getPropertyValue('border-bottom-width'), 10) }, minHeightValue = parseInt(taStyle.getPropertyValue('min-height'), 10), heightValue = parseInt(taStyle.getPropertyValue('height'), 10), minHeight = Math.max(minHeightValue, heightValue) - boxOuter.height, maxHeight = parseInt(taStyle.getPropertyValue('max-height'), 10), mirrored, active, copyStyle = ['font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-transform', 'word-spacing', 'text-indent']; // exit if elastic already applied (or is the mirror element) if ($ta.data('elastic')) { return; } // Opera returns max-height of -1 if not set maxHeight = maxHeight && maxHeight > 0 ? maxHeight : 9e4; // append mirror to the DOM if (mirror.parentNode !== document.body) { angular.element(document.body).append(mirror); } // set resize and apply elastic $ta.css({ 'resize': (resize === 'none' || resize === 'vertical') ? 'none' : 'horizontal' }).data('elastic', true); /* * methods */ function
() { var mirrorStyle = mirrorInitStyle; mirrored = ta; // copy the essential styles from the textarea to the mirror taStyle = getComputedStyle(ta); angular.forEach(copyStyle, function(val) { mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';'; }); mirror.setAttribute('style', mirrorStyle); } function adjust() { var taHeight, taComputedStyleWidth, mirrorHeight, width, overflow; if (mirrored !== ta) { initMirror(); } // active flag prevents actions in function from calling adjust again if (!active) { active = true; mirror.value = ta.value + append; // optional whitespace to improve animation mirror.style.overflowY = ta.style.overflowY; taHeight = ta.style.height === '' ? 'auto' : parseInt(ta.style.height, 10); taComputedStyleWidth = getComputedStyle(ta).getPropertyValue('width'); // ensure getComputedStyle has returned a readable 'used value' pixel width if (taComputedStyleWidth.substr(taComputedStyleWidth.length - 2, 2) === 'px') { // update mirror width in case the textarea width has changed width = parseInt(taComputedStyleWidth, 10) - boxOuter.width; mirror.style.width = width + 'px'; } mirrorHeight = mirror.scrollHeight; if (mirrorHeight > maxHeight) { mirrorHeight = maxHeight; overflow = 'scroll'; } else if (mirrorHeight < minHeight) { mirrorHeight = minHeight; } mirrorHeight += boxOuter.height; ta.style.overflowY = overflow || 'hidden'; if (taHeight !== mirrorHeight) { ta.style.height = mirrorHeight + 'px'; scope.$emit('elastic:resize', $ta); } // small delay to prevent an infinite loop $timeout(function() { active = false; }, 1); } } function forceAdjust() { active = false; adjust(); } /* * initialise */ // listen if ('onpropertychange' in ta && 'oninput' in ta) { // IE9 ta['oninput'] = ta.onkeyup = adjust; } else { ta['oninput'] = adjust; } $win.bind('resize', forceAdjust); scope.$watch(function() { return ngModel.$modelValue; }, function(newValue) { forceAdjust(); }); scope.$on('elastic:adjust', function() { initMirror(); forceAdjust(); }); $timeout(adjust); /* * destroy */ scope.$on('$destroy', function() { $mirror.remove(); $win.unbind('resize', forceAdjust); }); } }; } ]);
initMirror
identifier_name
elastic.js
/* * angular-elastic v2.4.2 * (c) 2014 Monospaced http://monospaced.com * License: MIT */ angular.module('monospaced.elastic', []) .constant('msdElasticConfig', { append: '' }) .directive('msdElastic', [ '$timeout', '$window', 'msdElasticConfig', function($timeout, $window, config) { 'use strict'; return { require: 'ngModel', restrict: 'A, C', link: function(scope, element, attrs, ngModel) { // cache a reference to the DOM element var ta = element[0], $ta = element; // ensure the element is a textarea, and browser is capable if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle)
// set these properties before measuring dimensions $ta.css({ 'overflow': 'hidden', 'overflow-y': 'hidden', 'word-wrap': 'break-word' }); // force text reflow var text = ta.value; ta.value = ''; ta.value = text; var append = attrs.msdElastic ? attrs.msdElastic.replace(/\\n/g, '\n') : config.append, $win = angular.element($window), mirrorInitStyle = 'position: absolute; top: -999px; right: auto; bottom: auto;' + 'left: 0; overflow: hidden; -webkit-box-sizing: content-box;' + '-moz-box-sizing: content-box; box-sizing: content-box;' + 'min-height: 0 !important; height: 0 !important; padding: 0;' + 'word-wrap: break-word; border: 0;', $mirror = angular.element('<textarea tabindex="-1" ' + 'style="' + mirrorInitStyle + '"/>').data('elastic', true), mirror = $mirror[0], taStyle = getComputedStyle(ta), resize = taStyle.getPropertyValue('resize'), borderBox = taStyle.getPropertyValue('box-sizing') === 'border-box' || taStyle.getPropertyValue('-moz-box-sizing') === 'border-box' || taStyle.getPropertyValue('-webkit-box-sizing') === 'border-box', boxOuter = !borderBox ? {width: 0, height: 0} : { width: parseInt(taStyle.getPropertyValue('border-right-width'), 10) + parseInt(taStyle.getPropertyValue('padding-right'), 10) + parseInt(taStyle.getPropertyValue('padding-left'), 10) + parseInt(taStyle.getPropertyValue('border-left-width'), 10), height: parseInt(taStyle.getPropertyValue('border-top-width'), 10) + parseInt(taStyle.getPropertyValue('padding-top'), 10) + parseInt(taStyle.getPropertyValue('padding-bottom'), 10) + parseInt(taStyle.getPropertyValue('border-bottom-width'), 10) }, minHeightValue = parseInt(taStyle.getPropertyValue('min-height'), 10), heightValue = parseInt(taStyle.getPropertyValue('height'), 10), minHeight = Math.max(minHeightValue, heightValue) - boxOuter.height, maxHeight = parseInt(taStyle.getPropertyValue('max-height'), 10), mirrored, active, copyStyle = ['font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-transform', 'word-spacing', 'text-indent']; // exit if elastic already applied (or is the mirror element) if ($ta.data('elastic')) { return; } // Opera returns max-height of -1 if not set maxHeight = maxHeight && maxHeight > 0 ? maxHeight : 9e4; // append mirror to the DOM if (mirror.parentNode !== document.body) { angular.element(document.body).append(mirror); } // set resize and apply elastic $ta.css({ 'resize': (resize === 'none' || resize === 'vertical') ? 'none' : 'horizontal' }).data('elastic', true); /* * methods */ function initMirror() { var mirrorStyle = mirrorInitStyle; mirrored = ta; // copy the essential styles from the textarea to the mirror taStyle = getComputedStyle(ta); angular.forEach(copyStyle, function(val) { mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';'; }); mirror.setAttribute('style', mirrorStyle); } function adjust() { var taHeight, taComputedStyleWidth, mirrorHeight, width, overflow; if (mirrored !== ta) { initMirror(); } // active flag prevents actions in function from calling adjust again if (!active) { active = true; mirror.value = ta.value + append; // optional whitespace to improve animation mirror.style.overflowY = ta.style.overflowY; taHeight = ta.style.height === '' ? 'auto' : parseInt(ta.style.height, 10); taComputedStyleWidth = getComputedStyle(ta).getPropertyValue('width'); // ensure getComputedStyle has returned a readable 'used value' pixel width if (taComputedStyleWidth.substr(taComputedStyleWidth.length - 2, 2) === 'px') { // update mirror width in case the textarea width has changed width = parseInt(taComputedStyleWidth, 10) - boxOuter.width; mirror.style.width = width + 'px'; } mirrorHeight = mirror.scrollHeight; if (mirrorHeight > maxHeight) { mirrorHeight = maxHeight; overflow = 'scroll'; } else if (mirrorHeight < minHeight) { mirrorHeight = minHeight; } mirrorHeight += boxOuter.height; ta.style.overflowY = overflow || 'hidden'; if (taHeight !== mirrorHeight) { ta.style.height = mirrorHeight + 'px'; scope.$emit('elastic:resize', $ta); } // small delay to prevent an infinite loop $timeout(function() { active = false; }, 1); } } function forceAdjust() { active = false; adjust(); } /* * initialise */ // listen if ('onpropertychange' in ta && 'oninput' in ta) { // IE9 ta['oninput'] = ta.onkeyup = adjust; } else { ta['oninput'] = adjust; } $win.bind('resize', forceAdjust); scope.$watch(function() { return ngModel.$modelValue; }, function(newValue) { forceAdjust(); }); scope.$on('elastic:adjust', function() { initMirror(); forceAdjust(); }); $timeout(adjust); /* * destroy */ scope.$on('$destroy', function() { $mirror.remove(); $win.unbind('resize', forceAdjust); }); } }; } ]);
{ return; }
conditional_block
elastic.js
/* * angular-elastic v2.4.2 * (c) 2014 Monospaced http://monospaced.com * License: MIT */ angular.module('monospaced.elastic', []) .constant('msdElasticConfig', { append: '' }) .directive('msdElastic', [ '$timeout', '$window', 'msdElasticConfig', function($timeout, $window, config) { 'use strict'; return { require: 'ngModel', restrict: 'A, C', link: function(scope, element, attrs, ngModel) { // cache a reference to the DOM element var ta = element[0], $ta = element; // ensure the element is a textarea, and browser is capable if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle) { return; } // set these properties before measuring dimensions $ta.css({ 'overflow': 'hidden', 'overflow-y': 'hidden', 'word-wrap': 'break-word' }); // force text reflow var text = ta.value; ta.value = ''; ta.value = text; var append = attrs.msdElastic ? attrs.msdElastic.replace(/\\n/g, '\n') : config.append, $win = angular.element($window), mirrorInitStyle = 'position: absolute; top: -999px; right: auto; bottom: auto;' + 'left: 0; overflow: hidden; -webkit-box-sizing: content-box;' + '-moz-box-sizing: content-box; box-sizing: content-box;' + 'min-height: 0 !important; height: 0 !important; padding: 0;' + 'word-wrap: break-word; border: 0;', $mirror = angular.element('<textarea tabindex="-1" ' + 'style="' + mirrorInitStyle + '"/>').data('elastic', true), mirror = $mirror[0], taStyle = getComputedStyle(ta), resize = taStyle.getPropertyValue('resize'), borderBox = taStyle.getPropertyValue('box-sizing') === 'border-box' || taStyle.getPropertyValue('-moz-box-sizing') === 'border-box' || taStyle.getPropertyValue('-webkit-box-sizing') === 'border-box', boxOuter = !borderBox ? {width: 0, height: 0} : { width: parseInt(taStyle.getPropertyValue('border-right-width'), 10) + parseInt(taStyle.getPropertyValue('padding-right'), 10) + parseInt(taStyle.getPropertyValue('padding-left'), 10) + parseInt(taStyle.getPropertyValue('border-left-width'), 10), height: parseInt(taStyle.getPropertyValue('border-top-width'), 10) + parseInt(taStyle.getPropertyValue('padding-top'), 10) + parseInt(taStyle.getPropertyValue('padding-bottom'), 10) + parseInt(taStyle.getPropertyValue('border-bottom-width'), 10) }, minHeightValue = parseInt(taStyle.getPropertyValue('min-height'), 10), heightValue = parseInt(taStyle.getPropertyValue('height'), 10), minHeight = Math.max(minHeightValue, heightValue) - boxOuter.height, maxHeight = parseInt(taStyle.getPropertyValue('max-height'), 10), mirrored, active, copyStyle = ['font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-transform', 'word-spacing', 'text-indent']; // exit if elastic already applied (or is the mirror element) if ($ta.data('elastic')) { return; } // Opera returns max-height of -1 if not set maxHeight = maxHeight && maxHeight > 0 ? maxHeight : 9e4; // append mirror to the DOM if (mirror.parentNode !== document.body) { angular.element(document.body).append(mirror); } // set resize and apply elastic $ta.css({ 'resize': (resize === 'none' || resize === 'vertical') ? 'none' : 'horizontal' }).data('elastic', true); /* * methods */ function initMirror() { var mirrorStyle = mirrorInitStyle; mirrored = ta; // copy the essential styles from the textarea to the mirror taStyle = getComputedStyle(ta); angular.forEach(copyStyle, function(val) { mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';'; }); mirror.setAttribute('style', mirrorStyle); } function adjust()
function forceAdjust() { active = false; adjust(); } /* * initialise */ // listen if ('onpropertychange' in ta && 'oninput' in ta) { // IE9 ta['oninput'] = ta.onkeyup = adjust; } else { ta['oninput'] = adjust; } $win.bind('resize', forceAdjust); scope.$watch(function() { return ngModel.$modelValue; }, function(newValue) { forceAdjust(); }); scope.$on('elastic:adjust', function() { initMirror(); forceAdjust(); }); $timeout(adjust); /* * destroy */ scope.$on('$destroy', function() { $mirror.remove(); $win.unbind('resize', forceAdjust); }); } }; } ]);
{ var taHeight, taComputedStyleWidth, mirrorHeight, width, overflow; if (mirrored !== ta) { initMirror(); } // active flag prevents actions in function from calling adjust again if (!active) { active = true; mirror.value = ta.value + append; // optional whitespace to improve animation mirror.style.overflowY = ta.style.overflowY; taHeight = ta.style.height === '' ? 'auto' : parseInt(ta.style.height, 10); taComputedStyleWidth = getComputedStyle(ta).getPropertyValue('width'); // ensure getComputedStyle has returned a readable 'used value' pixel width if (taComputedStyleWidth.substr(taComputedStyleWidth.length - 2, 2) === 'px') { // update mirror width in case the textarea width has changed width = parseInt(taComputedStyleWidth, 10) - boxOuter.width; mirror.style.width = width + 'px'; } mirrorHeight = mirror.scrollHeight; if (mirrorHeight > maxHeight) { mirrorHeight = maxHeight; overflow = 'scroll'; } else if (mirrorHeight < minHeight) { mirrorHeight = minHeight; } mirrorHeight += boxOuter.height; ta.style.overflowY = overflow || 'hidden'; if (taHeight !== mirrorHeight) { ta.style.height = mirrorHeight + 'px'; scope.$emit('elastic:resize', $ta); } // small delay to prevent an infinite loop $timeout(function() { active = false; }, 1); } }
identifier_body
elastic.js
/* * angular-elastic v2.4.2 * (c) 2014 Monospaced http://monospaced.com * License: MIT */ angular.module('monospaced.elastic', []) .constant('msdElasticConfig', { append: '' }) .directive('msdElastic', [ '$timeout', '$window', 'msdElasticConfig', function($timeout, $window, config) { 'use strict'; return { require: 'ngModel', restrict: 'A, C', link: function(scope, element, attrs, ngModel) { // cache a reference to the DOM element var ta = element[0], $ta = element; // ensure the element is a textarea, and browser is capable if (ta.nodeName !== 'TEXTAREA' || !$window.getComputedStyle) { return; } // set these properties before measuring dimensions $ta.css({ 'overflow': 'hidden', 'overflow-y': 'hidden', 'word-wrap': 'break-word' }); // force text reflow var text = ta.value; ta.value = ''; ta.value = text; var append = attrs.msdElastic ? attrs.msdElastic.replace(/\\n/g, '\n') : config.append, $win = angular.element($window), mirrorInitStyle = 'position: absolute; top: -999px; right: auto; bottom: auto;' + 'left: 0; overflow: hidden; -webkit-box-sizing: content-box;' + '-moz-box-sizing: content-box; box-sizing: content-box;' + 'min-height: 0 !important; height: 0 !important; padding: 0;' + 'word-wrap: break-word; border: 0;', $mirror = angular.element('<textarea tabindex="-1" ' + 'style="' + mirrorInitStyle + '"/>').data('elastic', true), mirror = $mirror[0], taStyle = getComputedStyle(ta), resize = taStyle.getPropertyValue('resize'), borderBox = taStyle.getPropertyValue('box-sizing') === 'border-box' || taStyle.getPropertyValue('-moz-box-sizing') === 'border-box' || taStyle.getPropertyValue('-webkit-box-sizing') === 'border-box', boxOuter = !borderBox ? {width: 0, height: 0} : { width: parseInt(taStyle.getPropertyValue('border-right-width'), 10) + parseInt(taStyle.getPropertyValue('padding-right'), 10) + parseInt(taStyle.getPropertyValue('padding-left'), 10) + parseInt(taStyle.getPropertyValue('border-left-width'), 10), height: parseInt(taStyle.getPropertyValue('border-top-width'), 10) + parseInt(taStyle.getPropertyValue('padding-top'), 10) + parseInt(taStyle.getPropertyValue('padding-bottom'), 10) + parseInt(taStyle.getPropertyValue('border-bottom-width'), 10) }, minHeightValue = parseInt(taStyle.getPropertyValue('min-height'), 10), heightValue = parseInt(taStyle.getPropertyValue('height'), 10), minHeight = Math.max(minHeightValue, heightValue) - boxOuter.height, maxHeight = parseInt(taStyle.getPropertyValue('max-height'), 10), mirrored, active, copyStyle = ['font-family', 'font-size', 'font-weight', 'font-style', 'letter-spacing', 'line-height', 'text-transform', 'word-spacing', 'text-indent']; // exit if elastic already applied (or is the mirror element) if ($ta.data('elastic')) { return; } // Opera returns max-height of -1 if not set maxHeight = maxHeight && maxHeight > 0 ? maxHeight : 9e4; // append mirror to the DOM if (mirror.parentNode !== document.body) { angular.element(document.body).append(mirror); } // set resize and apply elastic $ta.css({ 'resize': (resize === 'none' || resize === 'vertical') ? 'none' : 'horizontal' }).data('elastic', true); /* * methods */ function initMirror() { var mirrorStyle = mirrorInitStyle;
mirrorStyle += val + ':' + taStyle.getPropertyValue(val) + ';'; }); mirror.setAttribute('style', mirrorStyle); } function adjust() { var taHeight, taComputedStyleWidth, mirrorHeight, width, overflow; if (mirrored !== ta) { initMirror(); } // active flag prevents actions in function from calling adjust again if (!active) { active = true; mirror.value = ta.value + append; // optional whitespace to improve animation mirror.style.overflowY = ta.style.overflowY; taHeight = ta.style.height === '' ? 'auto' : parseInt(ta.style.height, 10); taComputedStyleWidth = getComputedStyle(ta).getPropertyValue('width'); // ensure getComputedStyle has returned a readable 'used value' pixel width if (taComputedStyleWidth.substr(taComputedStyleWidth.length - 2, 2) === 'px') { // update mirror width in case the textarea width has changed width = parseInt(taComputedStyleWidth, 10) - boxOuter.width; mirror.style.width = width + 'px'; } mirrorHeight = mirror.scrollHeight; if (mirrorHeight > maxHeight) { mirrorHeight = maxHeight; overflow = 'scroll'; } else if (mirrorHeight < minHeight) { mirrorHeight = minHeight; } mirrorHeight += boxOuter.height; ta.style.overflowY = overflow || 'hidden'; if (taHeight !== mirrorHeight) { ta.style.height = mirrorHeight + 'px'; scope.$emit('elastic:resize', $ta); } // small delay to prevent an infinite loop $timeout(function() { active = false; }, 1); } } function forceAdjust() { active = false; adjust(); } /* * initialise */ // listen if ('onpropertychange' in ta && 'oninput' in ta) { // IE9 ta['oninput'] = ta.onkeyup = adjust; } else { ta['oninput'] = adjust; } $win.bind('resize', forceAdjust); scope.$watch(function() { return ngModel.$modelValue; }, function(newValue) { forceAdjust(); }); scope.$on('elastic:adjust', function() { initMirror(); forceAdjust(); }); $timeout(adjust); /* * destroy */ scope.$on('$destroy', function() { $mirror.remove(); $win.unbind('resize', forceAdjust); }); } }; } ]);
mirrored = ta; // copy the essential styles from the textarea to the mirror taStyle = getComputedStyle(ta); angular.forEach(copyStyle, function(val) {
random_line_split
forms.py
from django import forms from selectable.forms import AutoCompleteSelectField from selectable.forms import AutoCompleteSelectWidget from opendata.catalog.lookups import CityLookup, CountyLookup from .models import Request class SearchForm(forms.Form): text = forms.CharField(required=False) class RequestForm(forms.ModelForm):
county = AutoCompleteSelectField( lookup_class=CountyLookup, required=False, widget=AutoCompleteSelectWidget( lookup_class=CountyLookup, attrs={"class": "suggestions-hidden suggestions-county"}, ) ) city = AutoCompleteSelectField( lookup_class=CityLookup, required=False, widget=AutoCompleteSelectWidget( lookup_class=CityLookup, attrs={"class": "suggestions-hidden suggestions-city"}, ) ) class Meta: model = Request exclude = ('suggested_by', 'resources', 'rating', 'status', ) class Media: js = ( "suggestions/js/form.js", )
identifier_body
forms.py
from django import forms from selectable.forms import AutoCompleteSelectField from selectable.forms import AutoCompleteSelectWidget from opendata.catalog.lookups import CityLookup, CountyLookup from .models import Request class SearchForm(forms.Form): text = forms.CharField(required=False) class RequestForm(forms.ModelForm): county = AutoCompleteSelectField( lookup_class=CountyLookup, required=False, widget=AutoCompleteSelectWidget( lookup_class=CountyLookup, attrs={"class": "suggestions-hidden suggestions-county"}, ) ) city = AutoCompleteSelectField( lookup_class=CityLookup, required=False, widget=AutoCompleteSelectWidget( lookup_class=CityLookup, attrs={"class": "suggestions-hidden suggestions-city"}, ) ) class Meta:
js = ( "suggestions/js/form.js", )
model = Request exclude = ('suggested_by', 'resources', 'rating', 'status', ) class Media:
random_line_split
forms.py
from django import forms from selectable.forms import AutoCompleteSelectField from selectable.forms import AutoCompleteSelectWidget from opendata.catalog.lookups import CityLookup, CountyLookup from .models import Request class SearchForm(forms.Form): text = forms.CharField(required=False) class
(forms.ModelForm): county = AutoCompleteSelectField( lookup_class=CountyLookup, required=False, widget=AutoCompleteSelectWidget( lookup_class=CountyLookup, attrs={"class": "suggestions-hidden suggestions-county"}, ) ) city = AutoCompleteSelectField( lookup_class=CityLookup, required=False, widget=AutoCompleteSelectWidget( lookup_class=CityLookup, attrs={"class": "suggestions-hidden suggestions-city"}, ) ) class Meta: model = Request exclude = ('suggested_by', 'resources', 'rating', 'status', ) class Media: js = ( "suggestions/js/form.js", )
RequestForm
identifier_name
list_filtering.js
function changeQueryStr(name, value) { var query = window.location.search.substring(1), newQuery = '?', notFound = true, vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair == '' || pair[0] == 'page') continue; if (pair[0] == name) { notFound = false; pair[1] = value; } if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; } } if (notFound && value.length > 0) { newQuery += name + '=' + value; } else if (newQuery.length == 1) { newQuery = ''; } else { newQuery = newQuery.slice(0,-1); } var loc = window.location, ajaxurl = '/ajax' + loc.pathname + newQuery, newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery; $.get(ajaxurl).done(function(data){ $('#ajax-content').html(data); init_pagination(); }); window.history.pushState({path:newurl},'',newurl); } function init_filtering_stories(jQuery) { $('#filtering input').change(function(){ var input = $(this), name = input[0].name, value=input.val(); changeQueryStr(name, value); }); } function init_pagination(jQuery) { $('.pager a').on('click', function(e){ e.preventDefault(); var value = $(this).closest('li').data('pageNum'); if (value) changeQueryStr('page', String(value)); });
$(document).ready(init_filtering_stories); $(document).ready(init_pagination);
}
random_line_split
list_filtering.js
function changeQueryStr(name, value)
function init_filtering_stories(jQuery) { $('#filtering input').change(function(){ var input = $(this), name = input[0].name, value=input.val(); changeQueryStr(name, value); }); } function init_pagination(jQuery) { $('.pager a').on('click', function(e){ e.preventDefault(); var value = $(this).closest('li').data('pageNum'); if (value) changeQueryStr('page', String(value)); }); } $(document).ready(init_filtering_stories); $(document).ready(init_pagination);
{ var query = window.location.search.substring(1), newQuery = '?', notFound = true, vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair == '' || pair[0] == 'page') continue; if (pair[0] == name) { notFound = false; pair[1] = value; } if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; } } if (notFound && value.length > 0) { newQuery += name + '=' + value; } else if (newQuery.length == 1) { newQuery = ''; } else { newQuery = newQuery.slice(0,-1); } var loc = window.location, ajaxurl = '/ajax' + loc.pathname + newQuery, newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery; $.get(ajaxurl).done(function(data){ $('#ajax-content').html(data); init_pagination(); }); window.history.pushState({path:newurl},'',newurl); }
identifier_body
list_filtering.js
function changeQueryStr(name, value) { var query = window.location.search.substring(1), newQuery = '?', notFound = true, vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair == '' || pair[0] == 'page') continue; if (pair[0] == name) { notFound = false; pair[1] = value; } if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; } } if (notFound && value.length > 0) { newQuery += name + '=' + value; } else if (newQuery.length == 1)
else { newQuery = newQuery.slice(0,-1); } var loc = window.location, ajaxurl = '/ajax' + loc.pathname + newQuery, newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery; $.get(ajaxurl).done(function(data){ $('#ajax-content').html(data); init_pagination(); }); window.history.pushState({path:newurl},'',newurl); } function init_filtering_stories(jQuery) { $('#filtering input').change(function(){ var input = $(this), name = input[0].name, value=input.val(); changeQueryStr(name, value); }); } function init_pagination(jQuery) { $('.pager a').on('click', function(e){ e.preventDefault(); var value = $(this).closest('li').data('pageNum'); if (value) changeQueryStr('page', String(value)); }); } $(document).ready(init_filtering_stories); $(document).ready(init_pagination);
{ newQuery = ''; }
conditional_block
list_filtering.js
function changeQueryStr(name, value) { var query = window.location.search.substring(1), newQuery = '?', notFound = true, vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair == '' || pair[0] == 'page') continue; if (pair[0] == name) { notFound = false; pair[1] = value; } if (pair[1].length > 0) { newQuery += pair[0] + '=' + pair[1] + '&'; } } if (notFound && value.length > 0) { newQuery += name + '=' + value; } else if (newQuery.length == 1) { newQuery = ''; } else { newQuery = newQuery.slice(0,-1); } var loc = window.location, ajaxurl = '/ajax' + loc.pathname + newQuery, newurl = loc.protocol + "//" + loc.host + loc.pathname + newQuery; $.get(ajaxurl).done(function(data){ $('#ajax-content').html(data); init_pagination(); }); window.history.pushState({path:newurl},'',newurl); } function init_filtering_stories(jQuery) { $('#filtering input').change(function(){ var input = $(this), name = input[0].name, value=input.val(); changeQueryStr(name, value); }); } function
(jQuery) { $('.pager a').on('click', function(e){ e.preventDefault(); var value = $(this).closest('li').data('pageNum'); if (value) changeQueryStr('page', String(value)); }); } $(document).ready(init_filtering_stories); $(document).ready(init_pagination);
init_pagination
identifier_name
gdcvault.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( HEADRequest, sanitized_Request, urlencode_postdata, ) class GDCVaultIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?' _NETRC_MACHINE = 'gdcvault' _TESTS = [ { 'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple', 'md5': '7ce8388f544c88b7ac11c7ab1b593704', 'info_dict': { 'id': '1019721', 'display_id': 'Doki-Doki-Universe-Sweet-Simple', 'ext': 'mp4', 'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)' } }, { 'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of', 'info_dict': { 'id': '1015683', 'display_id': 'Embracing-the-Dark-Art-of', 'ext': 'flv', 'title': 'Embracing the Dark Art of Mathematical Modeling in AI' }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or', 'md5': 'a5eb77996ef82118afbbe8e48731b98e', 'info_dict': { 'id': '1015301', 'display_id': 'Thexder-Meets-Windows-95-or', 'ext': 'flv', 'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment', }, 'skip': 'Requires login', }, { 'url': 'http://gdcvault.com/play/1020791/', 'only_matching': True, }, { # Hard-coded hostname 'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface', 'md5': 'a8efb6c31ed06ca8739294960b2dbabd', 'info_dict': { 'id': '1023460', 'ext': 'mp4', 'display_id': 'Tenacious-Design-and-The-Interface', 'title': 'Tenacious Design and The Interface of \'Destiny\'', }, }, { # Multiple audios 'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC', 'info_dict': { 'id': '1014631', 'ext': 'flv', 'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man', }, 'params': { 'skip_download': True, # Requires rtmpdump 'format': 'jp', # The japanese audio } }, { # gdc-player.html 'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo', 'info_dict': { 'id': '1435', 'display_id': 'An-American-engine-in-Tokyo', 'ext': 'flv', 'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT', }, 'params': { 'skip_download': True, # Requires rtmpdump }, }, ] def
(self, webpage_url, display_id): username, password = self._get_login_info() if username is None or password is None: self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.') return None mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url) login_url = mobj.group('root_url') + 'api/login.php' logout_url = mobj.group('root_url') + 'logout' login_form = { 'email': username, 'password': password, } request = sanitized_Request(login_url, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') self._download_webpage(request, display_id, 'Logging in') start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page') self._download_webpage(logout_url, display_id, 'Logging out') return start_page def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('name') or video_id webpage_url = 'http://www.gdcvault.com/play/' + video_id start_page = self._download_webpage(webpage_url, display_id) direct_url = self._search_regex( r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);', start_page, 'url', default=None) if direct_url: title = self._html_search_regex( r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>', start_page, 'title') video_url = 'http://www.gdcvault.com' + direct_url # resolve the url so that we can detect the correct extension head = self._request_webpage(HEADRequest(video_url), video_id) video_url = head.geturl() return { 'id': video_id, 'display_id': display_id, 'url': video_url, 'title': title, } PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>' xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root', default=None) if xml_root is None: # Probably need to authenticate login_res = self._login(webpage_url, display_id) if login_res is None: self.report_warning('Could not login.') else: start_page = login_res # Grab the url from the authenticated page xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root') xml_name = self._html_search_regex( r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>', start_page, 'xml filename', default=None) if xml_name is None: # Fallback to the older format xml_name = self._html_search_regex( r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>', start_page, 'xml filename') return { '_type': 'url_transparent', 'id': video_id, 'display_id': display_id, 'url': '%s/xml/%s' % (xml_root, xml_name), 'ie_key': 'DigitallySpeaking', }
_login
identifier_name
gdcvault.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( HEADRequest, sanitized_Request, urlencode_postdata, ) class GDCVaultIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?' _NETRC_MACHINE = 'gdcvault' _TESTS = [ { 'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple', 'md5': '7ce8388f544c88b7ac11c7ab1b593704', 'info_dict': { 'id': '1019721', 'display_id': 'Doki-Doki-Universe-Sweet-Simple', 'ext': 'mp4', 'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)' } }, { 'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of', 'info_dict': { 'id': '1015683', 'display_id': 'Embracing-the-Dark-Art-of', 'ext': 'flv', 'title': 'Embracing the Dark Art of Mathematical Modeling in AI' }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or', 'md5': 'a5eb77996ef82118afbbe8e48731b98e', 'info_dict': { 'id': '1015301', 'display_id': 'Thexder-Meets-Windows-95-or', 'ext': 'flv', 'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment', }, 'skip': 'Requires login', }, { 'url': 'http://gdcvault.com/play/1020791/', 'only_matching': True, }, { # Hard-coded hostname 'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface', 'md5': 'a8efb6c31ed06ca8739294960b2dbabd', 'info_dict': { 'id': '1023460', 'ext': 'mp4', 'display_id': 'Tenacious-Design-and-The-Interface', 'title': 'Tenacious Design and The Interface of \'Destiny\'', }, }, { # Multiple audios 'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC', 'info_dict': { 'id': '1014631', 'ext': 'flv', 'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man', }, 'params': { 'skip_download': True, # Requires rtmpdump 'format': 'jp', # The japanese audio } }, { # gdc-player.html 'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo', 'info_dict': { 'id': '1435', 'display_id': 'An-American-engine-in-Tokyo', 'ext': 'flv', 'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT', }, 'params': { 'skip_download': True, # Requires rtmpdump }, }, ] def _login(self, webpage_url, display_id): username, password = self._get_login_info() if username is None or password is None: self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.') return None mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url) login_url = mobj.group('root_url') + 'api/login.php' logout_url = mobj.group('root_url') + 'logout' login_form = { 'email': username, 'password': password, } request = sanitized_Request(login_url, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') self._download_webpage(request, display_id, 'Logging in') start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page') self._download_webpage(logout_url, display_id, 'Logging out') return start_page def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('name') or video_id webpage_url = 'http://www.gdcvault.com/play/' + video_id start_page = self._download_webpage(webpage_url, display_id) direct_url = self._search_regex( r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);', start_page, 'url', default=None) if direct_url: title = self._html_search_regex( r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>', start_page, 'title') video_url = 'http://www.gdcvault.com' + direct_url # resolve the url so that we can detect the correct extension head = self._request_webpage(HEADRequest(video_url), video_id) video_url = head.geturl() return { 'id': video_id, 'display_id': display_id, 'url': video_url, 'title': title, } PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>' xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root', default=None) if xml_root is None: # Probably need to authenticate login_res = self._login(webpage_url, display_id) if login_res is None: self.report_warning('Could not login.') else:
xml_name = self._html_search_regex( r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>', start_page, 'xml filename', default=None) if xml_name is None: # Fallback to the older format xml_name = self._html_search_regex( r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>', start_page, 'xml filename') return { '_type': 'url_transparent', 'id': video_id, 'display_id': display_id, 'url': '%s/xml/%s' % (xml_root, xml_name), 'ie_key': 'DigitallySpeaking', }
start_page = login_res # Grab the url from the authenticated page xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root')
conditional_block
gdcvault.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( HEADRequest, sanitized_Request, urlencode_postdata, ) class GDCVaultIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?' _NETRC_MACHINE = 'gdcvault' _TESTS = [ { 'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple', 'md5': '7ce8388f544c88b7ac11c7ab1b593704', 'info_dict': { 'id': '1019721', 'display_id': 'Doki-Doki-Universe-Sweet-Simple', 'ext': 'mp4', 'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)' } }, { 'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of', 'info_dict': { 'id': '1015683', 'display_id': 'Embracing-the-Dark-Art-of', 'ext': 'flv', 'title': 'Embracing the Dark Art of Mathematical Modeling in AI' }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or', 'md5': 'a5eb77996ef82118afbbe8e48731b98e', 'info_dict': { 'id': '1015301', 'display_id': 'Thexder-Meets-Windows-95-or', 'ext': 'flv', 'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment', }, 'skip': 'Requires login', }, { 'url': 'http://gdcvault.com/play/1020791/', 'only_matching': True, }, { # Hard-coded hostname 'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface', 'md5': 'a8efb6c31ed06ca8739294960b2dbabd', 'info_dict': { 'id': '1023460', 'ext': 'mp4', 'display_id': 'Tenacious-Design-and-The-Interface', 'title': 'Tenacious Design and The Interface of \'Destiny\'', }, }, { # Multiple audios 'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC', 'info_dict': { 'id': '1014631', 'ext': 'flv', 'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man', }, 'params': { 'skip_download': True, # Requires rtmpdump 'format': 'jp', # The japanese audio } }, { # gdc-player.html 'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo', 'info_dict': { 'id': '1435', 'display_id': 'An-American-engine-in-Tokyo', 'ext': 'flv', 'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT', }, 'params': { 'skip_download': True, # Requires rtmpdump }, }, ] def _login(self, webpage_url, display_id): username, password = self._get_login_info() if username is None or password is None: self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.') return None mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url) login_url = mobj.group('root_url') + 'api/login.php' logout_url = mobj.group('root_url') + 'logout'
login_form = { 'email': username, 'password': password, } request = sanitized_Request(login_url, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') self._download_webpage(request, display_id, 'Logging in') start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page') self._download_webpage(logout_url, display_id, 'Logging out') return start_page def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('name') or video_id webpage_url = 'http://www.gdcvault.com/play/' + video_id start_page = self._download_webpage(webpage_url, display_id) direct_url = self._search_regex( r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);', start_page, 'url', default=None) if direct_url: title = self._html_search_regex( r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>', start_page, 'title') video_url = 'http://www.gdcvault.com' + direct_url # resolve the url so that we can detect the correct extension head = self._request_webpage(HEADRequest(video_url), video_id) video_url = head.geturl() return { 'id': video_id, 'display_id': display_id, 'url': video_url, 'title': title, } PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>' xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root', default=None) if xml_root is None: # Probably need to authenticate login_res = self._login(webpage_url, display_id) if login_res is None: self.report_warning('Could not login.') else: start_page = login_res # Grab the url from the authenticated page xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root') xml_name = self._html_search_regex( r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>', start_page, 'xml filename', default=None) if xml_name is None: # Fallback to the older format xml_name = self._html_search_regex( r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>', start_page, 'xml filename') return { '_type': 'url_transparent', 'id': video_id, 'display_id': display_id, 'url': '%s/xml/%s' % (xml_root, xml_name), 'ie_key': 'DigitallySpeaking', }
random_line_split
gdcvault.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( HEADRequest, sanitized_Request, urlencode_postdata, ) class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?' _NETRC_MACHINE = 'gdcvault' _TESTS = [ { 'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple', 'md5': '7ce8388f544c88b7ac11c7ab1b593704', 'info_dict': { 'id': '1019721', 'display_id': 'Doki-Doki-Universe-Sweet-Simple', 'ext': 'mp4', 'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)' } }, { 'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of', 'info_dict': { 'id': '1015683', 'display_id': 'Embracing-the-Dark-Art-of', 'ext': 'flv', 'title': 'Embracing the Dark Art of Mathematical Modeling in AI' }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or', 'md5': 'a5eb77996ef82118afbbe8e48731b98e', 'info_dict': { 'id': '1015301', 'display_id': 'Thexder-Meets-Windows-95-or', 'ext': 'flv', 'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment', }, 'skip': 'Requires login', }, { 'url': 'http://gdcvault.com/play/1020791/', 'only_matching': True, }, { # Hard-coded hostname 'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface', 'md5': 'a8efb6c31ed06ca8739294960b2dbabd', 'info_dict': { 'id': '1023460', 'ext': 'mp4', 'display_id': 'Tenacious-Design-and-The-Interface', 'title': 'Tenacious Design and The Interface of \'Destiny\'', }, }, { # Multiple audios 'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC', 'info_dict': { 'id': '1014631', 'ext': 'flv', 'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man', }, 'params': { 'skip_download': True, # Requires rtmpdump 'format': 'jp', # The japanese audio } }, { # gdc-player.html 'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo', 'info_dict': { 'id': '1435', 'display_id': 'An-American-engine-in-Tokyo', 'ext': 'flv', 'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT', }, 'params': { 'skip_download': True, # Requires rtmpdump }, }, ] def _login(self, webpage_url, display_id): username, password = self._get_login_info() if username is None or password is None: self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.') return None mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url) login_url = mobj.group('root_url') + 'api/login.php' logout_url = mobj.group('root_url') + 'logout' login_form = { 'email': username, 'password': password, } request = sanitized_Request(login_url, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') self._download_webpage(request, display_id, 'Logging in') start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page') self._download_webpage(logout_url, display_id, 'Logging out') return start_page def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('name') or video_id webpage_url = 'http://www.gdcvault.com/play/' + video_id start_page = self._download_webpage(webpage_url, display_id) direct_url = self._search_regex( r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);', start_page, 'url', default=None) if direct_url: title = self._html_search_regex( r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>', start_page, 'title') video_url = 'http://www.gdcvault.com' + direct_url # resolve the url so that we can detect the correct extension head = self._request_webpage(HEADRequest(video_url), video_id) video_url = head.geturl() return { 'id': video_id, 'display_id': display_id, 'url': video_url, 'title': title, } PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>' xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root', default=None) if xml_root is None: # Probably need to authenticate login_res = self._login(webpage_url, display_id) if login_res is None: self.report_warning('Could not login.') else: start_page = login_res # Grab the url from the authenticated page xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root') xml_name = self._html_search_regex( r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>', start_page, 'xml filename', default=None) if xml_name is None: # Fallback to the older format xml_name = self._html_search_regex( r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>', start_page, 'xml filename') return { '_type': 'url_transparent', 'id': video_id, 'display_id': display_id, 'url': '%s/xml/%s' % (xml_root, xml_name), 'ie_key': 'DigitallySpeaking', }
identifier_body
util.js
/** * Module util.js * Its static common helpers methods */ (function (window) { if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } var util = {}; /** * Deeply extends two objects * @param {Object} destination The destination object, This object will change * @param {Object} source The custom options to extend destination by * @return {Object} The desination object */ util.extend = function (destination, source) { var property; for (property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; util.extend(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; /** * Clone object * @param {Object} source * @returns {*} */ util.objClone = function (source) { if (source === null || typeof source !== 'object') return source; var temp = source.constructor(); for (var key in source) temp[key] = util.objClone(source[key]); return temp; }; /** * Count object length * @param {Object} source * @returns {number} */ util.objLen = function (source) { var it = 0; for (var k in source) it++; return it; }; /** * Merge an object `src` into the object `objectBase` * @param objectBase main object of merge * @param src the elements of this object will be added/replaced to main object `obj` * @returns {*} object result */ util.objMerge = function (objectBase, src) { if (typeof objectBase !== 'object' || typeof src !== 'object') return false; if (Object.key) { Object.keys(src).forEach(function (key) { objectBase[key] = src[key]; }); return objectBase; } else { for (var key in src) if (src.hasOwnProperty(key)) objectBase[key] = src[key]; return objectBase; } }; /** * Merge objects if `objectBase` key not exists * @param objectBase * @param src * @returns {*} */ util.objMergeNotExists = function (objectBase, src) { for (var key in src) if (objectBase[key] === undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge objects if `objectBase` key is exists * @param objectBase * @param src * @returns {*} */ util.objMergeOnlyExists = function (objectBase, src) { for (var key in src) if (objectBase[key] !== undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge an array `src` into the array `arrBase` * @param arrBase * @param src * @returns {*} */ util.arrMerge = function (arrBase, src) { if (!Array.isArray(arrBase) || !Array.isArray(src)) return false; for (var i = 0; i < src.length; i++) arrBase.push(src[i]) return arrBase; }; /** * Computes the difference of arrays * Compares arr1 against one or more other arrays and returns the values in arr1 * that are not present in any of the other arrays. * @param arr1 * @param arr2 * @returns {*} */ util.arrDiff = function (arr1, arr2) { if (util.isArr(arr1) && util.isArr(arr2)) { return arr1.slice(0).filter(function (item) { return arr2.indexOf(item) === -1; }) } return false; }; util.objToArr = function (obj) { return [].slice.call(obj); }; util.realObjToArr = function (obj) { var arr = []; for (var key in obj) arr.push(obj[key]) return arr; }; util.cloneFunction = function (func) { var temp = function temporary() { return func.apply(this, arguments); }; for (var key in this) { if (this.hasOwnProperty(key)) { temp[key] = this[key]; } } return temp; }; /** * Check on typeof is string a param * @param param * @returns {boolean} */ util.isStr = function (param) { return typeof param === 'string'; }; /** * Check on typeof is array a param * @param param * @returns {boolean} */ util.isArr = function (param) { return Array.isArray(param); }; /** * Check on typeof is object a param * @param param * @returns {boolean} */ util.isObj = function (param) { return (param !== null && typeof param == 'object'); }; /** * Determine param is a number or a numeric string * @param param * @returns {boolean} */ util.isNum = function (param) { return !isNaN(param); }; // Determine whether a variable is empty util.isEmpty = function (param) { return (param === "" || param === 0 || param === "0" || param === null || param === undefined || param === false || (util.isArr(param) && param.length === 0)); }; util.isHtml = function (param) { if (util.isNode(param)) return true; return util.isNode(util.html2node(param)); }; util.isNode = function (param) { var types = [1, 9, 11]; if (typeof param === 'object' && types.indexOf(param.nodeType) !== -1) return true; else return false; }; /** * * Node.ELEMENT_NODE - 1 - ELEMENT * Node.TEXT_NODE - 3 - TEXT * Node.PROCESSING_INSTRUCTION_NODE - 7 - PROCESSING * Node.COMMENT_NODE - 8 - COMMENT * Node.DOCUMENT_NODE - 9 - DOCUMENT * Node.DOCUMENT_TYPE_NODE - 10 - DOCUMENT_TYPE * Node.DOCUMENT_FRAGMENT_NODE - 11 - FRAGMENT * Uses: Util.isNodeType(elem, 'element') */ util.isNodeType = function (param, type) { type = String((type ? type : 1)).toUpperCase(); if (typeof param === 'object') { switch (type) { case '1': case 'ELEMENT': return param.nodeType === Node.ELEMENT_NODE; break; case '3': case 'TEXT': return param.nodeType === Node.TEXT_NODE; break; case '7': case 'PROCESSING': return param.nodeType === Node.PROCESSING_INSTRUCTION_NODE; break; case '8': case 'COMMENT': return param.nodeType === Node.COMMENT_NODE; break; case '9': case 'DOCUMENT': return param.nodeType === Node.DOCUMENT_NODE; break; case '10': case 'DOCUMENT_TYPE': return param.nodeType === Node.DOCUMENT_TYPE_NODE; break; case '11': case 'FRAGMENT': return param.nodeType === Node.DOCUMENT_FRAGMENT_NODE; break; default: return false; } } else return false; }; /** * Determine param to undefined type * @param param * @returns {boolean} */ util.defined = function (param) { return typeof(param) != 'undefined'; }; /** * Javascript object to JSON data * @param data */ util.objToJson = function (data) { return JSON.stringify(data); }; /** * JSON data to Javascript object * @param data */ util.jsonToObj = function (data) { return JSON.parse(data); }; /** * Cleans the array of empty elements * @param src * @returns {Array} */ util.cleanArr = function (src) { var arr = []; for (var i = 0; i < src.length; i++) if (src[i]) arr.push(src[i]); return arr; }; /** * Return type of data as name object "Array", "Object", "String", "Number", "Function" * @param data * @returns {string} */ util.typeOf = function (data) { return Object.prototype.toString.call(data).slice(8, -1); }; /** * Convert HTML form to encode URI string * @param form * @param asObject * @returns {*} */ util.formData = function (form, asObject) { var obj = {}, str = ''; for (var i = 0; i < form.length; i++) { var f = form[i]; if (f.type == 'submit' || f.type == 'button') continue; if ((f.type == 'radio' || f.type == 'checkbox') && f.checked == false) continue; var fName = f.nodeName.toLowerCase(); if (fName == 'input' || fName == 'select' || fName == 'textarea') { obj[f.name] = f.value; str += ((str == '') ? '' : '&') + f.name + '=' + encodeURIComponent(f.value); } } return (asObject === true) ? obj : str; }; /** * HTML string convert to DOM Elements Object * @param data * @returns {*} */ util.toNode = function (data) { var parser = new DOMParser(); var node = parser.parseFromString(data, "text/xml"); console.log(node); if (typeof node == 'object' && node.firstChild.nodeType == Node.ELEMENT_NODE) return node.firstChild; else return false; }; /** * Removes duplicate values from an array * @param arr * @returns {Array} */ util.uniqueArr = function (arr) { var tmp = []; for (var i = 0; i < arr.length; i++) { if (tmp.indexOf(arr[i]) == "-1") tmp.push(arr[i]); } return tmp; }; /** * Reads entire file into a string, synchronously * This function uses XmlHttpRequest and cannot retrieve resource from different domain. * @param url * @returns {*|string|null|string} */ util.fileGetContents = function (url) { var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch (e) { } } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText; }; /** * Calculates the position and size of elements. * * @param elem * @returns {{y: number, x: number, width: number, height: number}} */ util.getPosition = function (elem) { var top = 0, left = 0; if (elem.getBoundingClientRect) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return {y: Math.round(top), x: Math.round(left), width: elem.offsetWidth, height: elem.offsetHeight}; } else { //fallback to naive approach while (elem) { top = top + parseInt(elem.offsetTop, 10); left = left + parseInt(elem.offsetLeft, 10); elem = elem.offsetParent; } return {x: left, y: top, width: elem.offsetWidth, height: elem.offsetHeight}; } }; /** * Returns the coordinates of the mouse on any element * @param event * @param element * @returns {{x: number, y: number}} */ util.getMousePosition = function (event, element) { var positions = {x: 0, y: 0}; element = element || document.body; if (element instanceof HTMLElement && event instanceof MouseEvent) { if (element.getBoundingClientRect) { var rect = element.getBoundingClientRect(); positions.x = event.clientX - rect.left; positions.y = event.clientY - rect.top; } else { positions.x = event.pageX - element.offsetLeft; positions.y = event.pageY - element.offsetTop; } } return positions; }; /** * Creator of styles, return style-element or style-text. * * <pre>var style = createStyle('body','font-size:10px'); *style.add('body','font-size:10px') // added style *style.add( {'background-color':'red'} ) // added style *style.getString() // style-text *style.getObject() // style-element</pre> * * @param selector name of selector styles * @param property string "display:object" or object {'background-color':'red'} * @returns {*} return object with methods : getString(), getObject(), add() */ util.createStyle = function (selector, property) { var o = { content: '', getString: function () { return '<style rel="stylesheet">' + "\n" + o.content + "\n" + '</style>'; }, getObject: function () { var st = document.createElement('style'); st.setAttribute('rel', 'stylesheet'); st.textContent = o.content; return st; }, add: function (select, prop) { if (typeof prop === 'string') { o.content += select + "{" + ( (prop.substr(-1) == ';') ? prop : prop + ';' ) + "}"; } else if (typeof prop === 'object') { o.content += select + "{"; for (var key in prop) o.content += key + ':' + prop[key] + ';'; o.content += "}"; } return this; } }; return o.add(selector, property); }; /** * Create new NodeElement * @param tag element tag name 'p, div, h3 ... other' * @param attrs object with attributes key=value * @param inner text, html or NodeElement * @returns {Element} */ util.createElement = function (tag, attrs, inner) { var elem = document.createElement(tag); if (typeof attrs === 'object') { for (var key in attrs) elem.setAttribute(key, attrs[key]); } if (typeof inner === 'string') { elem.innerHTML = inner; } else if (typeof inner === 'object') { elem.appendChild(elem); } return elem; }; /** * Returns a random integer between min, max, if not specified the default of 0 to 100 * @param min * @param max * @returns {number} */ util.rand = function (min, max) { min = min || 0; max = max || 100; return Math.floor(Math.random() * (max - min + 1) + min); }; /** * Returns random string color, HEX format * @returns {string} */ util.randColor = function () { var letters = '0123456789ABCDEF'.split(''), color = '#'; for (var i = 0; i < 6; i++) color += letters[Math.floor(Math.random() * 16)]; return color; }; /** * Converts degrees to radians * @param deg * @returns {number} */ util.degreesToRadians = function (deg) { return (deg * Math.PI) / 180; }; /** * Converts radians to degrees * @param rad * @returns {number} */ util.radiansToDegrees = function (rad) { return (rad * 180) / Math.PI; }; /** * The calculation of the distance between points * The point is an object with properties `x` and `y` {x:100,y:100} * @param point1 * @param point2 * @returns {number} */ util.distanceBetween = function (point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; return Math.sqrt(dx * dx + dy * dy); }; /** * Encode URI params * @param data Object key=value * @returns {*} query string */ util.encodeData = function (data) { if (typeof data === 'string') return data; if (typeof data !== 'object') return ''; var convertData = []; Object.keys(data).forEach(function (key) { convertData.push(key + '=' + encodeURIComponent(data[key])); }); return convertData.join('&'); }; /** * Parse URI Request data into object * @param url * @returns {{}} */ util.parseGet = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; if (parser.search.length > 1) { parser.search.substr(1).split('&').forEach(function (part) { var item = part.split('='); params[item[0]] = decodeURIComponent(item[1]); }); } return params; }; /** * Parse Url string/location into object * @param url * @returns {{}} */ util.parseUrl = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; params.protocol = parser.protocol; params.host = parser.host; params.hostname = parser.hostname; params.port = parser.port; params.pathname = parser.pathname; params.hash = parser.hash; params.search = parser.search; params.get = util.parseGet(parser.search); return params; }; util.each = function (data, callback) { if (util.isArr(data)) { for (var i = 0; i < data.length; i++) callback.call(null, data[i]); } else if (util.isObj(data)) { for (var k in data) callback.call(null, k, data[k]); } else return false; }; util.ucfirst = function (string) { return string && string[0].toUpperCase() + string.slice(1); }; util.node2html = function (element) { var container = document.createElement("div"); container.appendChild(element.cloneNode(true)); return container.innerHTML; }; util.html2node = function (string) { var i, fragment = document.createDocumentFragment(), container = document.createElement("div"); container.innerHTML = string; while (i = container.firstChild) fragment.appendChild(i); return fragment.childNodes.length === 1 ? fragment.firstChild : fragment; }; util.base64encode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64encoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; for (var i = 0; i < str.length;) { chr1 = str.charCodeAt(i++); chr2 = str.charCodeAt(i++); chr3 = str.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = isNaN(chr2) ? 64 : (((chr2 & 15) << 2) | (chr3 >> 6)); enc4 = isNaN(chr3) ? 64 : (chr3 & 63); b64encoded += b64chars.charAt(enc1) + b64chars.charAt(enc2) + b64chars.charAt(enc3) + b64chars.charAt(enc4); } return b64encoded; }; util.base64decode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64decoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; str = str.replace(/[^a-z0-9\+\/\=]/gi, ''); for (var i = 0; i < str.length;) { enc1 = b64chars.indexOf(str.charAt(i++)); enc2 = b64chars.indexOf(str.charAt(i++)); enc3 = b64chars.indexOf(str.charAt(i++)); enc4 = b64chars.indexOf(str.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; b64decoded = b64decoded + String.fromCharCode(chr1); if (enc3 < 64) { b64decoded += String.fromCharCode(chr2); } if (enc4 < 64) { b64decoded += String.fromCharCode(chr3); } } return b64decoded; }; /** * Cross-browser function for the character of the event keypress: * @param event event.type must keypress * @returns {*} */ util.getChar = function (event) { if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; }; util.Date = function () { }; util.Date.time = function (date) { "use strict"; return date instanceof Date ? date.getTime() : (new Date).getTime(); }; /** * Add days to some date * @param day number of days. 0.04 - 1 hour, 0.5 - 12 hour, 1 - 1 day * @param startDate type Date, start date * @returns {*} type Date */ util.Date.addDays = function (day, startDate) { var date = startDate ? new Date(startDate) : new Date(); date.setTime(date.getTime() + (day * 86400000)); return date; }; util.Date.daysBetween = function (date1, date2) { var ONE_DAY = 86400000, date1_ms = date1.getTime(), date2_ms = date2.getTime(); return Math.round((Math.abs(date1_ms - date2_ms)) / ONE_DAY) }; util.Storage = function (name, value) { if (!name) { return false; } else if (value === undefined) { return util.Storage.get(name); } else if (!value) { return util.Storage.remove(name); } else { return util.Storage.set(name, value); } }; util.Storage.set = function (name, value) { try { value = JSON.stringify(value) } catch (error) { } return window.localStorage.setItem(name, value); }; util.Storage.get = function (name) { var value = window.localStorage.getItem(name); if (value) try { value = JSON.parse(value) } catch (error) { } return value; }; util.Storage.remove = function (name) { return window.localStorage.removeItem(name); }; util.Storage.key = function (name) { return window.localStorage.key(key); }; // when invoked, will empty all keys out of the storage. util.Storage.clear = function () { return window.localStorage.clear(); }; // returns an integer representing the number of data items stored in the Storage object. util.Storage.length = function () { return window.localStorage.length; }; /** * возвращает cookie с именем name, если есть, если нет, то undefined * @param name * @param value */ util.Cookie = function (name, value) { "use strict"; if (value === undefined) { return util.Cookie.get(name); } else if (value === false || value === null) { util.Cookie.delete(name); } else { util.Cookie.set(name, value); } }; util.Cookie.get = function (name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; }; /** * * @param name * @param value * @param {{}} options {expires: 0, path: '/', domain: 'site.com', secure: false} * expires - ms, Date, -1, 0 */ util.Cookie.set = function (name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires == "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires * 1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for (var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; }; util.Cookie.delete = util.Cookie.remove = function (name, option) { "use strict"; option = typeof option === 'object' ? option : {}; option.expires = -1; util.Cookie.set(name, "", option); }; util.getURLParameter = function (name) { var reg = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]; return reg === null ? undefined : decodeURI(reg); }; /** * An asynchronous for-each loop * * @param {Array} array The array to loop through * * @param {function} done Callback function (when the loop is finished or an error occurs) * * @param {function} iterator * The logic for each iteration. Signature is `function(item, index, next)`. * Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop. * Or don't call `next` at all to break out of the loop. */ util.asyncForEach = function (array, done, iterator) { var i = 0; next(); function next(err) { if (err)
done(err); else if (i >= array.length) done(); else if (i < array.length) { var item = array[i++]; setTimeout(function () { iterator(item, i - 1, next); }, 0); } } }; /** * Calls the callback in a given interval until it returns true * @param {function} callback * @param {number} interval in milliseconds */ util.waitFor = function (callback, interval) { var internalCallback = function () { if (callback() !== true) { setTimeout(internalCallback, interval); } }; internalCallback(); }; /** * Remove item from array * @param item * @param stack * @returns {Array} */ util.rmInArray = function (item, stack) { var newStack = []; for (var i = 0; i < stack.length; i++) { if (stack[i] && stack[i] != item) newStack.push(stack[i]); } return newStack; }; /** * @param text * @returns {string|void|XML} */ util.toTranslit = function (text) { return text.replace(/([а-яё])|([\s_-])|([^a-z\d])/gi, function (all, ch, space, words, i) { if (space || words) return space ? '-' : ''; var code = ch.charCodeAt(0), index = code == 1025 || code == 1105 ? 0 : code > 1071 ? code - 1071 : code - 1039, t = ['yo', 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya']; return t[index]; }); }; window.Util = util; })(window);
identifier_name
util.js
/** * Module util.js * Its static common helpers methods */ (function (window) { if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } var util = {}; /** * Deeply extends two objects * @param {Object} destination The destination object, This object will change * @param {Object} source The custom options to extend destination by * @return {Object} The desination object */ util.extend = function (destination, source) { var property; for (property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; util.extend(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; /** * Clone object * @param {Object} source * @returns {*} */ util.objClone = function (source) { if (source === null || typeof source !== 'object') return source; var temp = source.constructor(); for (var key in source) temp[key] = util.objClone(source[key]); return temp; }; /** * Count object length * @param {Object} source * @returns {number} */ util.objLen = function (source) { var it = 0; for (var k in source) it++; return it; }; /** * Merge an object `src` into the object `objectBase` * @param objectBase main object of merge * @param src the elements of this object will be added/replaced to main object `obj` * @returns {*} object result */ util.objMerge = function (objectBase, src) { if (typeof objectBase !== 'object' || typeof src !== 'object') return false; if (Object.key) { Object.keys(src).forEach(function (key) { objectBase[key] = src[key]; }); return objectBase; } else { for (var key in src) if (src.hasOwnProperty(key)) objectBase[key] = src[key]; return objectBase; } }; /** * Merge objects if `objectBase` key not exists * @param objectBase * @param src * @returns {*} */ util.objMergeNotExists = function (objectBase, src) { for (var key in src) if (objectBase[key] === undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge objects if `objectBase` key is exists * @param objectBase
* @returns {*} */ util.objMergeOnlyExists = function (objectBase, src) { for (var key in src) if (objectBase[key] !== undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge an array `src` into the array `arrBase` * @param arrBase * @param src * @returns {*} */ util.arrMerge = function (arrBase, src) { if (!Array.isArray(arrBase) || !Array.isArray(src)) return false; for (var i = 0; i < src.length; i++) arrBase.push(src[i]) return arrBase; }; /** * Computes the difference of arrays * Compares arr1 against one or more other arrays and returns the values in arr1 * that are not present in any of the other arrays. * @param arr1 * @param arr2 * @returns {*} */ util.arrDiff = function (arr1, arr2) { if (util.isArr(arr1) && util.isArr(arr2)) { return arr1.slice(0).filter(function (item) { return arr2.indexOf(item) === -1; }) } return false; }; util.objToArr = function (obj) { return [].slice.call(obj); }; util.realObjToArr = function (obj) { var arr = []; for (var key in obj) arr.push(obj[key]) return arr; }; util.cloneFunction = function (func) { var temp = function temporary() { return func.apply(this, arguments); }; for (var key in this) { if (this.hasOwnProperty(key)) { temp[key] = this[key]; } } return temp; }; /** * Check on typeof is string a param * @param param * @returns {boolean} */ util.isStr = function (param) { return typeof param === 'string'; }; /** * Check on typeof is array a param * @param param * @returns {boolean} */ util.isArr = function (param) { return Array.isArray(param); }; /** * Check on typeof is object a param * @param param * @returns {boolean} */ util.isObj = function (param) { return (param !== null && typeof param == 'object'); }; /** * Determine param is a number or a numeric string * @param param * @returns {boolean} */ util.isNum = function (param) { return !isNaN(param); }; // Determine whether a variable is empty util.isEmpty = function (param) { return (param === "" || param === 0 || param === "0" || param === null || param === undefined || param === false || (util.isArr(param) && param.length === 0)); }; util.isHtml = function (param) { if (util.isNode(param)) return true; return util.isNode(util.html2node(param)); }; util.isNode = function (param) { var types = [1, 9, 11]; if (typeof param === 'object' && types.indexOf(param.nodeType) !== -1) return true; else return false; }; /** * * Node.ELEMENT_NODE - 1 - ELEMENT * Node.TEXT_NODE - 3 - TEXT * Node.PROCESSING_INSTRUCTION_NODE - 7 - PROCESSING * Node.COMMENT_NODE - 8 - COMMENT * Node.DOCUMENT_NODE - 9 - DOCUMENT * Node.DOCUMENT_TYPE_NODE - 10 - DOCUMENT_TYPE * Node.DOCUMENT_FRAGMENT_NODE - 11 - FRAGMENT * Uses: Util.isNodeType(elem, 'element') */ util.isNodeType = function (param, type) { type = String((type ? type : 1)).toUpperCase(); if (typeof param === 'object') { switch (type) { case '1': case 'ELEMENT': return param.nodeType === Node.ELEMENT_NODE; break; case '3': case 'TEXT': return param.nodeType === Node.TEXT_NODE; break; case '7': case 'PROCESSING': return param.nodeType === Node.PROCESSING_INSTRUCTION_NODE; break; case '8': case 'COMMENT': return param.nodeType === Node.COMMENT_NODE; break; case '9': case 'DOCUMENT': return param.nodeType === Node.DOCUMENT_NODE; break; case '10': case 'DOCUMENT_TYPE': return param.nodeType === Node.DOCUMENT_TYPE_NODE; break; case '11': case 'FRAGMENT': return param.nodeType === Node.DOCUMENT_FRAGMENT_NODE; break; default: return false; } } else return false; }; /** * Determine param to undefined type * @param param * @returns {boolean} */ util.defined = function (param) { return typeof(param) != 'undefined'; }; /** * Javascript object to JSON data * @param data */ util.objToJson = function (data) { return JSON.stringify(data); }; /** * JSON data to Javascript object * @param data */ util.jsonToObj = function (data) { return JSON.parse(data); }; /** * Cleans the array of empty elements * @param src * @returns {Array} */ util.cleanArr = function (src) { var arr = []; for (var i = 0; i < src.length; i++) if (src[i]) arr.push(src[i]); return arr; }; /** * Return type of data as name object "Array", "Object", "String", "Number", "Function" * @param data * @returns {string} */ util.typeOf = function (data) { return Object.prototype.toString.call(data).slice(8, -1); }; /** * Convert HTML form to encode URI string * @param form * @param asObject * @returns {*} */ util.formData = function (form, asObject) { var obj = {}, str = ''; for (var i = 0; i < form.length; i++) { var f = form[i]; if (f.type == 'submit' || f.type == 'button') continue; if ((f.type == 'radio' || f.type == 'checkbox') && f.checked == false) continue; var fName = f.nodeName.toLowerCase(); if (fName == 'input' || fName == 'select' || fName == 'textarea') { obj[f.name] = f.value; str += ((str == '') ? '' : '&') + f.name + '=' + encodeURIComponent(f.value); } } return (asObject === true) ? obj : str; }; /** * HTML string convert to DOM Elements Object * @param data * @returns {*} */ util.toNode = function (data) { var parser = new DOMParser(); var node = parser.parseFromString(data, "text/xml"); console.log(node); if (typeof node == 'object' && node.firstChild.nodeType == Node.ELEMENT_NODE) return node.firstChild; else return false; }; /** * Removes duplicate values from an array * @param arr * @returns {Array} */ util.uniqueArr = function (arr) { var tmp = []; for (var i = 0; i < arr.length; i++) { if (tmp.indexOf(arr[i]) == "-1") tmp.push(arr[i]); } return tmp; }; /** * Reads entire file into a string, synchronously * This function uses XmlHttpRequest and cannot retrieve resource from different domain. * @param url * @returns {*|string|null|string} */ util.fileGetContents = function (url) { var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch (e) { } } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText; }; /** * Calculates the position and size of elements. * * @param elem * @returns {{y: number, x: number, width: number, height: number}} */ util.getPosition = function (elem) { var top = 0, left = 0; if (elem.getBoundingClientRect) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return {y: Math.round(top), x: Math.round(left), width: elem.offsetWidth, height: elem.offsetHeight}; } else { //fallback to naive approach while (elem) { top = top + parseInt(elem.offsetTop, 10); left = left + parseInt(elem.offsetLeft, 10); elem = elem.offsetParent; } return {x: left, y: top, width: elem.offsetWidth, height: elem.offsetHeight}; } }; /** * Returns the coordinates of the mouse on any element * @param event * @param element * @returns {{x: number, y: number}} */ util.getMousePosition = function (event, element) { var positions = {x: 0, y: 0}; element = element || document.body; if (element instanceof HTMLElement && event instanceof MouseEvent) { if (element.getBoundingClientRect) { var rect = element.getBoundingClientRect(); positions.x = event.clientX - rect.left; positions.y = event.clientY - rect.top; } else { positions.x = event.pageX - element.offsetLeft; positions.y = event.pageY - element.offsetTop; } } return positions; }; /** * Creator of styles, return style-element or style-text. * * <pre>var style = createStyle('body','font-size:10px'); *style.add('body','font-size:10px') // added style *style.add( {'background-color':'red'} ) // added style *style.getString() // style-text *style.getObject() // style-element</pre> * * @param selector name of selector styles * @param property string "display:object" or object {'background-color':'red'} * @returns {*} return object with methods : getString(), getObject(), add() */ util.createStyle = function (selector, property) { var o = { content: '', getString: function () { return '<style rel="stylesheet">' + "\n" + o.content + "\n" + '</style>'; }, getObject: function () { var st = document.createElement('style'); st.setAttribute('rel', 'stylesheet'); st.textContent = o.content; return st; }, add: function (select, prop) { if (typeof prop === 'string') { o.content += select + "{" + ( (prop.substr(-1) == ';') ? prop : prop + ';' ) + "}"; } else if (typeof prop === 'object') { o.content += select + "{"; for (var key in prop) o.content += key + ':' + prop[key] + ';'; o.content += "}"; } return this; } }; return o.add(selector, property); }; /** * Create new NodeElement * @param tag element tag name 'p, div, h3 ... other' * @param attrs object with attributes key=value * @param inner text, html or NodeElement * @returns {Element} */ util.createElement = function (tag, attrs, inner) { var elem = document.createElement(tag); if (typeof attrs === 'object') { for (var key in attrs) elem.setAttribute(key, attrs[key]); } if (typeof inner === 'string') { elem.innerHTML = inner; } else if (typeof inner === 'object') { elem.appendChild(elem); } return elem; }; /** * Returns a random integer between min, max, if not specified the default of 0 to 100 * @param min * @param max * @returns {number} */ util.rand = function (min, max) { min = min || 0; max = max || 100; return Math.floor(Math.random() * (max - min + 1) + min); }; /** * Returns random string color, HEX format * @returns {string} */ util.randColor = function () { var letters = '0123456789ABCDEF'.split(''), color = '#'; for (var i = 0; i < 6; i++) color += letters[Math.floor(Math.random() * 16)]; return color; }; /** * Converts degrees to radians * @param deg * @returns {number} */ util.degreesToRadians = function (deg) { return (deg * Math.PI) / 180; }; /** * Converts radians to degrees * @param rad * @returns {number} */ util.radiansToDegrees = function (rad) { return (rad * 180) / Math.PI; }; /** * The calculation of the distance between points * The point is an object with properties `x` and `y` {x:100,y:100} * @param point1 * @param point2 * @returns {number} */ util.distanceBetween = function (point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; return Math.sqrt(dx * dx + dy * dy); }; /** * Encode URI params * @param data Object key=value * @returns {*} query string */ util.encodeData = function (data) { if (typeof data === 'string') return data; if (typeof data !== 'object') return ''; var convertData = []; Object.keys(data).forEach(function (key) { convertData.push(key + '=' + encodeURIComponent(data[key])); }); return convertData.join('&'); }; /** * Parse URI Request data into object * @param url * @returns {{}} */ util.parseGet = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; if (parser.search.length > 1) { parser.search.substr(1).split('&').forEach(function (part) { var item = part.split('='); params[item[0]] = decodeURIComponent(item[1]); }); } return params; }; /** * Parse Url string/location into object * @param url * @returns {{}} */ util.parseUrl = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; params.protocol = parser.protocol; params.host = parser.host; params.hostname = parser.hostname; params.port = parser.port; params.pathname = parser.pathname; params.hash = parser.hash; params.search = parser.search; params.get = util.parseGet(parser.search); return params; }; util.each = function (data, callback) { if (util.isArr(data)) { for (var i = 0; i < data.length; i++) callback.call(null, data[i]); } else if (util.isObj(data)) { for (var k in data) callback.call(null, k, data[k]); } else return false; }; util.ucfirst = function (string) { return string && string[0].toUpperCase() + string.slice(1); }; util.node2html = function (element) { var container = document.createElement("div"); container.appendChild(element.cloneNode(true)); return container.innerHTML; }; util.html2node = function (string) { var i, fragment = document.createDocumentFragment(), container = document.createElement("div"); container.innerHTML = string; while (i = container.firstChild) fragment.appendChild(i); return fragment.childNodes.length === 1 ? fragment.firstChild : fragment; }; util.base64encode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64encoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; for (var i = 0; i < str.length;) { chr1 = str.charCodeAt(i++); chr2 = str.charCodeAt(i++); chr3 = str.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = isNaN(chr2) ? 64 : (((chr2 & 15) << 2) | (chr3 >> 6)); enc4 = isNaN(chr3) ? 64 : (chr3 & 63); b64encoded += b64chars.charAt(enc1) + b64chars.charAt(enc2) + b64chars.charAt(enc3) + b64chars.charAt(enc4); } return b64encoded; }; util.base64decode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64decoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; str = str.replace(/[^a-z0-9\+\/\=]/gi, ''); for (var i = 0; i < str.length;) { enc1 = b64chars.indexOf(str.charAt(i++)); enc2 = b64chars.indexOf(str.charAt(i++)); enc3 = b64chars.indexOf(str.charAt(i++)); enc4 = b64chars.indexOf(str.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; b64decoded = b64decoded + String.fromCharCode(chr1); if (enc3 < 64) { b64decoded += String.fromCharCode(chr2); } if (enc4 < 64) { b64decoded += String.fromCharCode(chr3); } } return b64decoded; }; /** * Cross-browser function for the character of the event keypress: * @param event event.type must keypress * @returns {*} */ util.getChar = function (event) { if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; }; util.Date = function () { }; util.Date.time = function (date) { "use strict"; return date instanceof Date ? date.getTime() : (new Date).getTime(); }; /** * Add days to some date * @param day number of days. 0.04 - 1 hour, 0.5 - 12 hour, 1 - 1 day * @param startDate type Date, start date * @returns {*} type Date */ util.Date.addDays = function (day, startDate) { var date = startDate ? new Date(startDate) : new Date(); date.setTime(date.getTime() + (day * 86400000)); return date; }; util.Date.daysBetween = function (date1, date2) { var ONE_DAY = 86400000, date1_ms = date1.getTime(), date2_ms = date2.getTime(); return Math.round((Math.abs(date1_ms - date2_ms)) / ONE_DAY) }; util.Storage = function (name, value) { if (!name) { return false; } else if (value === undefined) { return util.Storage.get(name); } else if (!value) { return util.Storage.remove(name); } else { return util.Storage.set(name, value); } }; util.Storage.set = function (name, value) { try { value = JSON.stringify(value) } catch (error) { } return window.localStorage.setItem(name, value); }; util.Storage.get = function (name) { var value = window.localStorage.getItem(name); if (value) try { value = JSON.parse(value) } catch (error) { } return value; }; util.Storage.remove = function (name) { return window.localStorage.removeItem(name); }; util.Storage.key = function (name) { return window.localStorage.key(key); }; // when invoked, will empty all keys out of the storage. util.Storage.clear = function () { return window.localStorage.clear(); }; // returns an integer representing the number of data items stored in the Storage object. util.Storage.length = function () { return window.localStorage.length; }; /** * возвращает cookie с именем name, если есть, если нет, то undefined * @param name * @param value */ util.Cookie = function (name, value) { "use strict"; if (value === undefined) { return util.Cookie.get(name); } else if (value === false || value === null) { util.Cookie.delete(name); } else { util.Cookie.set(name, value); } }; util.Cookie.get = function (name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; }; /** * * @param name * @param value * @param {{}} options {expires: 0, path: '/', domain: 'site.com', secure: false} * expires - ms, Date, -1, 0 */ util.Cookie.set = function (name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires == "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires * 1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for (var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; }; util.Cookie.delete = util.Cookie.remove = function (name, option) { "use strict"; option = typeof option === 'object' ? option : {}; option.expires = -1; util.Cookie.set(name, "", option); }; util.getURLParameter = function (name) { var reg = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]; return reg === null ? undefined : decodeURI(reg); }; /** * An asynchronous for-each loop * * @param {Array} array The array to loop through * * @param {function} done Callback function (when the loop is finished or an error occurs) * * @param {function} iterator * The logic for each iteration. Signature is `function(item, index, next)`. * Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop. * Or don't call `next` at all to break out of the loop. */ util.asyncForEach = function (array, done, iterator) { var i = 0; next(); function next(err) { if (err) done(err); else if (i >= array.length) done(); else if (i < array.length) { var item = array[i++]; setTimeout(function () { iterator(item, i - 1, next); }, 0); } } }; /** * Calls the callback in a given interval until it returns true * @param {function} callback * @param {number} interval in milliseconds */ util.waitFor = function (callback, interval) { var internalCallback = function () { if (callback() !== true) { setTimeout(internalCallback, interval); } }; internalCallback(); }; /** * Remove item from array * @param item * @param stack * @returns {Array} */ util.rmInArray = function (item, stack) { var newStack = []; for (var i = 0; i < stack.length; i++) { if (stack[i] && stack[i] != item) newStack.push(stack[i]); } return newStack; }; /** * @param text * @returns {string|void|XML} */ util.toTranslit = function (text) { return text.replace(/([а-яё])|([\s_-])|([^a-z\d])/gi, function (all, ch, space, words, i) { if (space || words) return space ? '-' : ''; var code = ch.charCodeAt(0), index = code == 1025 || code == 1105 ? 0 : code > 1071 ? code - 1071 : code - 1039, t = ['yo', 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya']; return t[index]; }); }; window.Util = util; })(window);
* @param src
random_line_split
util.js
/** * Module util.js * Its static common helpers methods */ (function (window) { if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } var util = {}; /** * Deeply extends two objects * @param {Object} destination The destination object, This object will change * @param {Object} source The custom options to extend destination by * @return {Object} The desination object */ util.extend = function (destination, source) { var property; for (property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; util.extend(destination[property], source[property]); } else { destination[property] = source[property]; } } return destination; }; /** * Clone object * @param {Object} source * @returns {*} */ util.objClone = function (source) { if (source === null || typeof source !== 'object') return source; var temp = source.constructor(); for (var key in source) temp[key] = util.objClone(source[key]); return temp; }; /** * Count object length * @param {Object} source * @returns {number} */ util.objLen = function (source) { var it = 0; for (var k in source) it++; return it; }; /** * Merge an object `src` into the object `objectBase` * @param objectBase main object of merge * @param src the elements of this object will be added/replaced to main object `obj` * @returns {*} object result */ util.objMerge = function (objectBase, src) { if (typeof objectBase !== 'object' || typeof src !== 'object') return false; if (Object.key) { Object.keys(src).forEach(function (key) { objectBase[key] = src[key]; }); return objectBase; } else { for (var key in src) if (src.hasOwnProperty(key)) objectBase[key] = src[key]; return objectBase; } }; /** * Merge objects if `objectBase` key not exists * @param objectBase * @param src * @returns {*} */ util.objMergeNotExists = function (objectBase, src) { for (var key in src) if (objectBase[key] === undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge objects if `objectBase` key is exists * @param objectBase * @param src * @returns {*} */ util.objMergeOnlyExists = function (objectBase, src) { for (var key in src) if (objectBase[key] !== undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge an array `src` into the array `arrBase` * @param arrBase * @param src * @returns {*} */ util.arrMerge = function (arrBase, src) { if (!Array.isArray(arrBase) || !Array.isArray(src)) return false; for (var i = 0; i < src.length; i++) arrBase.push(src[i]) return arrBase; }; /** * Computes the difference of arrays * Compares arr1 against one or more other arrays and returns the values in arr1 * that are not present in any of the other arrays. * @param arr1 * @param arr2 * @returns {*} */ util.arrDiff = function (arr1, arr2) { if (util.isArr(arr1) && util.isArr(arr2)) { return arr1.slice(0).filter(function (item) { return arr2.indexOf(item) === -1; }) } return false; }; util.objToArr = function (obj) { return [].slice.call(obj); }; util.realObjToArr = function (obj) { var arr = []; for (var key in obj) arr.push(obj[key]) return arr; }; util.cloneFunction = function (func) { var temp = function temporary() { return func.apply(this, arguments); }; for (var key in this) { if (this.hasOwnProperty(key)) { temp[key] = this[key]; } } return temp; }; /** * Check on typeof is string a param * @param param * @returns {boolean} */ util.isStr = function (param) { return typeof param === 'string'; }; /** * Check on typeof is array a param * @param param * @returns {boolean} */ util.isArr = function (param) { return Array.isArray(param); }; /** * Check on typeof is object a param * @param param * @returns {boolean} */ util.isObj = function (param) { return (param !== null && typeof param == 'object'); }; /** * Determine param is a number or a numeric string * @param param * @returns {boolean} */ util.isNum = function (param) { return !isNaN(param); }; // Determine whether a variable is empty util.isEmpty = function (param) { return (param === "" || param === 0 || param === "0" || param === null || param === undefined || param === false || (util.isArr(param) && param.length === 0)); }; util.isHtml = function (param) { if (util.isNode(param)) return true; return util.isNode(util.html2node(param)); }; util.isNode = function (param) { var types = [1, 9, 11]; if (typeof param === 'object' && types.indexOf(param.nodeType) !== -1) return true; else return false; }; /** * * Node.ELEMENT_NODE - 1 - ELEMENT * Node.TEXT_NODE - 3 - TEXT * Node.PROCESSING_INSTRUCTION_NODE - 7 - PROCESSING * Node.COMMENT_NODE - 8 - COMMENT * Node.DOCUMENT_NODE - 9 - DOCUMENT * Node.DOCUMENT_TYPE_NODE - 10 - DOCUMENT_TYPE * Node.DOCUMENT_FRAGMENT_NODE - 11 - FRAGMENT * Uses: Util.isNodeType(elem, 'element') */ util.isNodeType = function (param, type) { type = String((type ? type : 1)).toUpperCase(); if (typeof param === 'object') { switch (type) { case '1': case 'ELEMENT': return param.nodeType === Node.ELEMENT_NODE; break; case '3': case 'TEXT': return param.nodeType === Node.TEXT_NODE; break; case '7': case 'PROCESSING': return param.nodeType === Node.PROCESSING_INSTRUCTION_NODE; break; case '8': case 'COMMENT': return param.nodeType === Node.COMMENT_NODE; break; case '9': case 'DOCUMENT': return param.nodeType === Node.DOCUMENT_NODE; break; case '10': case 'DOCUMENT_TYPE': return param.nodeType === Node.DOCUMENT_TYPE_NODE; break; case '11': case 'FRAGMENT': return param.nodeType === Node.DOCUMENT_FRAGMENT_NODE; break; default: return false; } } else return false; }; /** * Determine param to undefined type * @param param * @returns {boolean} */ util.defined = function (param) { return typeof(param) != 'undefined'; }; /** * Javascript object to JSON data * @param data */ util.objToJson = function (data) { return JSON.stringify(data); }; /** * JSON data to Javascript object * @param data */ util.jsonToObj = function (data) { return JSON.parse(data); }; /** * Cleans the array of empty elements * @param src * @returns {Array} */ util.cleanArr = function (src) { var arr = []; for (var i = 0; i < src.length; i++) if (src[i]) arr.push(src[i]); return arr; }; /** * Return type of data as name object "Array", "Object", "String", "Number", "Function" * @param data * @returns {string} */ util.typeOf = function (data) { return Object.prototype.toString.call(data).slice(8, -1); }; /** * Convert HTML form to encode URI string * @param form * @param asObject * @returns {*} */ util.formData = function (form, asObject) { var obj = {}, str = ''; for (var i = 0; i < form.length; i++) { var f = form[i]; if (f.type == 'submit' || f.type == 'button') continue; if ((f.type == 'radio' || f.type == 'checkbox') && f.checked == false) continue; var fName = f.nodeName.toLowerCase(); if (fName == 'input' || fName == 'select' || fName == 'textarea') { obj[f.name] = f.value; str += ((str == '') ? '' : '&') + f.name + '=' + encodeURIComponent(f.value); } } return (asObject === true) ? obj : str; }; /** * HTML string convert to DOM Elements Object * @param data * @returns {*} */ util.toNode = function (data) { var parser = new DOMParser(); var node = parser.parseFromString(data, "text/xml"); console.log(node); if (typeof node == 'object' && node.firstChild.nodeType == Node.ELEMENT_NODE) return node.firstChild; else return false; }; /** * Removes duplicate values from an array * @param arr * @returns {Array} */ util.uniqueArr = function (arr) { var tmp = []; for (var i = 0; i < arr.length; i++) { if (tmp.indexOf(arr[i]) == "-1") tmp.push(arr[i]); } return tmp; }; /** * Reads entire file into a string, synchronously * This function uses XmlHttpRequest and cannot retrieve resource from different domain. * @param url * @returns {*|string|null|string} */ util.fileGetContents = function (url) { var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch (e) { } } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText; }; /** * Calculates the position and size of elements. * * @param elem * @returns {{y: number, x: number, width: number, height: number}} */ util.getPosition = function (elem) { var top = 0, left = 0; if (elem.getBoundingClientRect) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return {y: Math.round(top), x: Math.round(left), width: elem.offsetWidth, height: elem.offsetHeight}; } else { //fallback to naive approach while (elem) { top = top + parseInt(elem.offsetTop, 10); left = left + parseInt(elem.offsetLeft, 10); elem = elem.offsetParent; } return {x: left, y: top, width: elem.offsetWidth, height: elem.offsetHeight}; } }; /** * Returns the coordinates of the mouse on any element * @param event * @param element * @returns {{x: number, y: number}} */ util.getMousePosition = function (event, element) { var positions = {x: 0, y: 0}; element = element || document.body; if (element instanceof HTMLElement && event instanceof MouseEvent) { if (element.getBoundingClientRect) { var rect = element.getBoundingClientRect(); positions.x = event.clientX - rect.left; positions.y = event.clientY - rect.top; } else { positions.x = event.pageX - element.offsetLeft; positions.y = event.pageY - element.offsetTop; } } return positions; }; /** * Creator of styles, return style-element or style-text. * * <pre>var style = createStyle('body','font-size:10px'); *style.add('body','font-size:10px') // added style *style.add( {'background-color':'red'} ) // added style *style.getString() // style-text *style.getObject() // style-element</pre> * * @param selector name of selector styles * @param property string "display:object" or object {'background-color':'red'} * @returns {*} return object with methods : getString(), getObject(), add() */ util.createStyle = function (selector, property) { var o = { content: '', getString: function () { return '<style rel="stylesheet">' + "\n" + o.content + "\n" + '</style>'; }, getObject: function () { var st = document.createElement('style'); st.setAttribute('rel', 'stylesheet'); st.textContent = o.content; return st; }, add: function (select, prop) { if (typeof prop === 'string') { o.content += select + "{" + ( (prop.substr(-1) == ';') ? prop : prop + ';' ) + "}"; } else if (typeof prop === 'object') { o.content += select + "{"; for (var key in prop) o.content += key + ':' + prop[key] + ';'; o.content += "}"; } return this; } }; return o.add(selector, property); }; /** * Create new NodeElement * @param tag element tag name 'p, div, h3 ... other' * @param attrs object with attributes key=value * @param inner text, html or NodeElement * @returns {Element} */ util.createElement = function (tag, attrs, inner) { var elem = document.createElement(tag); if (typeof attrs === 'object') { for (var key in attrs) elem.setAttribute(key, attrs[key]); } if (typeof inner === 'string') { elem.innerHTML = inner; } else if (typeof inner === 'object') { elem.appendChild(elem); } return elem; }; /** * Returns a random integer between min, max, if not specified the default of 0 to 100 * @param min * @param max * @returns {number} */ util.rand = function (min, max) { min = min || 0; max = max || 100; return Math.floor(Math.random() * (max - min + 1) + min); }; /** * Returns random string color, HEX format * @returns {string} */ util.randColor = function () { var letters = '0123456789ABCDEF'.split(''), color = '#'; for (var i = 0; i < 6; i++) color += letters[Math.floor(Math.random() * 16)]; return color; }; /** * Converts degrees to radians * @param deg * @returns {number} */ util.degreesToRadians = function (deg) { return (deg * Math.PI) / 180; }; /** * Converts radians to degrees * @param rad * @returns {number} */ util.radiansToDegrees = function (rad) { return (rad * 180) / Math.PI; }; /** * The calculation of the distance between points * The point is an object with properties `x` and `y` {x:100,y:100} * @param point1 * @param point2 * @returns {number} */ util.distanceBetween = function (point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; return Math.sqrt(dx * dx + dy * dy); }; /** * Encode URI params * @param data Object key=value * @returns {*} query string */ util.encodeData = function (data) { if (typeof data === 'string') return data; if (typeof data !== 'object') return ''; var convertData = []; Object.keys(data).forEach(function (key) { convertData.push(key + '=' + encodeURIComponent(data[key])); }); return convertData.join('&'); }; /** * Parse URI Request data into object * @param url * @returns {{}} */ util.parseGet = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; if (parser.search.length > 1) { parser.search.substr(1).split('&').forEach(function (part) { var item = part.split('='); params[item[0]] = decodeURIComponent(item[1]); }); } return params; }; /** * Parse Url string/location into object * @param url * @returns {{}} */ util.parseUrl = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; params.protocol = parser.protocol; params.host = parser.host; params.hostname = parser.hostname; params.port = parser.port; params.pathname = parser.pathname; params.hash = parser.hash; params.search = parser.search; params.get = util.parseGet(parser.search); return params; }; util.each = function (data, callback) { if (util.isArr(data)) { for (var i = 0; i < data.length; i++) callback.call(null, data[i]); } else if (util.isObj(data)) { for (var k in data) callback.call(null, k, data[k]); } else return false; }; util.ucfirst = function (string) { return string && string[0].toUpperCase() + string.slice(1); }; util.node2html = function (element) { var container = document.createElement("div"); container.appendChild(element.cloneNode(true)); return container.innerHTML; }; util.html2node = function (string) { var i, fragment = document.createDocumentFragment(), container = document.createElement("div"); container.innerHTML = string; while (i = container.firstChild) fragment.appendChild(i); return fragment.childNodes.length === 1 ? fragment.firstChild : fragment; }; util.base64encode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64encoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; for (var i = 0; i < str.length;) { chr1 = str.charCodeAt(i++); chr2 = str.charCodeAt(i++); chr3 = str.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = isNaN(chr2) ? 64 : (((chr2 & 15) << 2) | (chr3 >> 6)); enc4 = isNaN(chr3) ? 64 : (chr3 & 63); b64encoded += b64chars.charAt(enc1) + b64chars.charAt(enc2) + b64chars.charAt(enc3) + b64chars.charAt(enc4); } return b64encoded; }; util.base64decode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64decoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; str = str.replace(/[^a-z0-9\+\/\=]/gi, ''); for (var i = 0; i < str.length;) { enc1 = b64chars.indexOf(str.charAt(i++)); enc2 = b64chars.indexOf(str.charAt(i++)); enc3 = b64chars.indexOf(str.charAt(i++)); enc4 = b64chars.indexOf(str.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; b64decoded = b64decoded + String.fromCharCode(chr1); if (enc3 < 64) { b64decoded += String.fromCharCode(chr2); } if (enc4 < 64) { b64decoded += String.fromCharCode(chr3); } } return b64decoded; }; /** * Cross-browser function for the character of the event keypress: * @param event event.type must keypress * @returns {*} */ util.getChar = function (event) { if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; }; util.Date = function () { }; util.Date.time = function (date) { "use strict"; return date instanceof Date ? date.getTime() : (new Date).getTime(); }; /** * Add days to some date * @param day number of days. 0.04 - 1 hour, 0.5 - 12 hour, 1 - 1 day * @param startDate type Date, start date * @returns {*} type Date */ util.Date.addDays = function (day, startDate) { var date = startDate ? new Date(startDate) : new Date(); date.setTime(date.getTime() + (day * 86400000)); return date; }; util.Date.daysBetween = function (date1, date2) { var ONE_DAY = 86400000, date1_ms = date1.getTime(), date2_ms = date2.getTime(); return Math.round((Math.abs(date1_ms - date2_ms)) / ONE_DAY) }; util.Storage = function (name, value) { if (!name) { return false; } else if (value === undefined) { return util.Storage.get(name); } else if (!value) { return util.Storage.remove(name); } else { return util.Storage.set(name, value); } }; util.Storage.set = function (name, value) { try { value = JSON.stringify(value) } catch (error) { } return window.localStorage.setItem(name, value); }; util.Storage.get = function (name) { var value = window.localStorage.getItem(name); if (value) try { value = JSON.parse(value) } catch (error) { } return value; }; util.Storage.remove = function (name) { return window.localStorage.removeItem(name); }; util.Storage.key = function (name) { return window.localStorage.key(key); }; // when invoked, will empty all keys out of the storage. util.Storage.clear = function () { return window.localStorage.clear(); }; // returns an integer representing the number of data items stored in the Storage object. util.Storage.length = function () { return window.localStorage.length; }; /** * возвращает cookie с именем name, если есть, если нет, то undefined * @param name * @param value */ util.Cookie = function (name, value) { "use strict"; if (value === undefined) { return util.Cookie.get(name); } else if (value === false || value === null) { util.Cookie.delete(name); } else { util.Cookie.set(name, value); } }; util.Cookie.get = function (name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; }; /** * * @param name * @param value * @param {{}} options {expires: 0, path: '/', domain: 'site.com', secure: false} * expires - ms, Date, -1, 0 */ util.Cookie.set = function (name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires == "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires * 1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for (var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; }; util.Cookie.delete = util.Cookie.remove = function (name, option) { "use strict"; option = typeof option === 'object' ? option : {}; option.expires = -1; util.Cookie.set(name, "", option); }; util.getURLParameter = function (name) { var reg = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]; return reg === null ? undefined : decodeURI(reg); }; /** * An asynchronous for-each loop * * @param {Array} array The array to loop through * * @param {function} done Callback function (when the loop is finished or an error occurs) * * @param {function} iterator * The logic for each iteration. Signature is `function(item, index, next)`. * Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop. * Or don't call `next` at all to break out of the loop. */ util.asyncForEach = function (array, done, iterator) { var i = 0; next(); function next(err) { if (err)
callback in a given interval until it returns true * @param {function} callback * @param {number} interval in milliseconds */ util.waitFor = function (callback, interval) { var internalCallback = function () { if (callback() !== true) { setTimeout(internalCallback, interval); } }; internalCallback(); }; /** * Remove item from array * @param item * @param stack * @returns {Array} */ util.rmInArray = function (item, stack) { var newStack = []; for (var i = 0; i < stack.length; i++) { if (stack[i] && stack[i] != item) newStack.push(stack[i]); } return newStack; }; /** * @param text * @returns {string|void|XML} */ util.toTranslit = function (text) { return text.replace(/([а-яё])|([\s_-])|([^a-z\d])/gi, function (all, ch, space, words, i) { if (space || words) return space ? '-' : ''; var code = ch.charCodeAt(0), index = code == 1025 || code == 1105 ? 0 : code > 1071 ? code - 1071 : code - 1039, t = ['yo', 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya']; return t[index]; }); }; window.Util = util; })(window);
done(err); else if (i >= array.length) done(); else if (i < array.length) { var item = array[i++]; setTimeout(function () { iterator(item, i - 1, next); }, 0); } } }; /** * Calls the
identifier_body
util.js
/** * Module util.js * Its static common helpers methods */ (function (window) { if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } var util = {}; /** * Deeply extends two objects * @param {Object} destination The destination object, This object will change * @param {Object} source The custom options to extend destination by * @return {Object} The desination object */ util.extend = function (destination, source) { var property; for (property in source) { if (source[property] && source[property].constructor && source[property].constructor === Object) { destination[property] = destination[property] || {}; util.extend(destination[property], source[property]); } else
} return destination; }; /** * Clone object * @param {Object} source * @returns {*} */ util.objClone = function (source) { if (source === null || typeof source !== 'object') return source; var temp = source.constructor(); for (var key in source) temp[key] = util.objClone(source[key]); return temp; }; /** * Count object length * @param {Object} source * @returns {number} */ util.objLen = function (source) { var it = 0; for (var k in source) it++; return it; }; /** * Merge an object `src` into the object `objectBase` * @param objectBase main object of merge * @param src the elements of this object will be added/replaced to main object `obj` * @returns {*} object result */ util.objMerge = function (objectBase, src) { if (typeof objectBase !== 'object' || typeof src !== 'object') return false; if (Object.key) { Object.keys(src).forEach(function (key) { objectBase[key] = src[key]; }); return objectBase; } else { for (var key in src) if (src.hasOwnProperty(key)) objectBase[key] = src[key]; return objectBase; } }; /** * Merge objects if `objectBase` key not exists * @param objectBase * @param src * @returns {*} */ util.objMergeNotExists = function (objectBase, src) { for (var key in src) if (objectBase[key] === undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge objects if `objectBase` key is exists * @param objectBase * @param src * @returns {*} */ util.objMergeOnlyExists = function (objectBase, src) { for (var key in src) if (objectBase[key] !== undefined) objectBase[key] = src[key]; return objectBase; }; /** * Merge an array `src` into the array `arrBase` * @param arrBase * @param src * @returns {*} */ util.arrMerge = function (arrBase, src) { if (!Array.isArray(arrBase) || !Array.isArray(src)) return false; for (var i = 0; i < src.length; i++) arrBase.push(src[i]) return arrBase; }; /** * Computes the difference of arrays * Compares arr1 against one or more other arrays and returns the values in arr1 * that are not present in any of the other arrays. * @param arr1 * @param arr2 * @returns {*} */ util.arrDiff = function (arr1, arr2) { if (util.isArr(arr1) && util.isArr(arr2)) { return arr1.slice(0).filter(function (item) { return arr2.indexOf(item) === -1; }) } return false; }; util.objToArr = function (obj) { return [].slice.call(obj); }; util.realObjToArr = function (obj) { var arr = []; for (var key in obj) arr.push(obj[key]) return arr; }; util.cloneFunction = function (func) { var temp = function temporary() { return func.apply(this, arguments); }; for (var key in this) { if (this.hasOwnProperty(key)) { temp[key] = this[key]; } } return temp; }; /** * Check on typeof is string a param * @param param * @returns {boolean} */ util.isStr = function (param) { return typeof param === 'string'; }; /** * Check on typeof is array a param * @param param * @returns {boolean} */ util.isArr = function (param) { return Array.isArray(param); }; /** * Check on typeof is object a param * @param param * @returns {boolean} */ util.isObj = function (param) { return (param !== null && typeof param == 'object'); }; /** * Determine param is a number or a numeric string * @param param * @returns {boolean} */ util.isNum = function (param) { return !isNaN(param); }; // Determine whether a variable is empty util.isEmpty = function (param) { return (param === "" || param === 0 || param === "0" || param === null || param === undefined || param === false || (util.isArr(param) && param.length === 0)); }; util.isHtml = function (param) { if (util.isNode(param)) return true; return util.isNode(util.html2node(param)); }; util.isNode = function (param) { var types = [1, 9, 11]; if (typeof param === 'object' && types.indexOf(param.nodeType) !== -1) return true; else return false; }; /** * * Node.ELEMENT_NODE - 1 - ELEMENT * Node.TEXT_NODE - 3 - TEXT * Node.PROCESSING_INSTRUCTION_NODE - 7 - PROCESSING * Node.COMMENT_NODE - 8 - COMMENT * Node.DOCUMENT_NODE - 9 - DOCUMENT * Node.DOCUMENT_TYPE_NODE - 10 - DOCUMENT_TYPE * Node.DOCUMENT_FRAGMENT_NODE - 11 - FRAGMENT * Uses: Util.isNodeType(elem, 'element') */ util.isNodeType = function (param, type) { type = String((type ? type : 1)).toUpperCase(); if (typeof param === 'object') { switch (type) { case '1': case 'ELEMENT': return param.nodeType === Node.ELEMENT_NODE; break; case '3': case 'TEXT': return param.nodeType === Node.TEXT_NODE; break; case '7': case 'PROCESSING': return param.nodeType === Node.PROCESSING_INSTRUCTION_NODE; break; case '8': case 'COMMENT': return param.nodeType === Node.COMMENT_NODE; break; case '9': case 'DOCUMENT': return param.nodeType === Node.DOCUMENT_NODE; break; case '10': case 'DOCUMENT_TYPE': return param.nodeType === Node.DOCUMENT_TYPE_NODE; break; case '11': case 'FRAGMENT': return param.nodeType === Node.DOCUMENT_FRAGMENT_NODE; break; default: return false; } } else return false; }; /** * Determine param to undefined type * @param param * @returns {boolean} */ util.defined = function (param) { return typeof(param) != 'undefined'; }; /** * Javascript object to JSON data * @param data */ util.objToJson = function (data) { return JSON.stringify(data); }; /** * JSON data to Javascript object * @param data */ util.jsonToObj = function (data) { return JSON.parse(data); }; /** * Cleans the array of empty elements * @param src * @returns {Array} */ util.cleanArr = function (src) { var arr = []; for (var i = 0; i < src.length; i++) if (src[i]) arr.push(src[i]); return arr; }; /** * Return type of data as name object "Array", "Object", "String", "Number", "Function" * @param data * @returns {string} */ util.typeOf = function (data) { return Object.prototype.toString.call(data).slice(8, -1); }; /** * Convert HTML form to encode URI string * @param form * @param asObject * @returns {*} */ util.formData = function (form, asObject) { var obj = {}, str = ''; for (var i = 0; i < form.length; i++) { var f = form[i]; if (f.type == 'submit' || f.type == 'button') continue; if ((f.type == 'radio' || f.type == 'checkbox') && f.checked == false) continue; var fName = f.nodeName.toLowerCase(); if (fName == 'input' || fName == 'select' || fName == 'textarea') { obj[f.name] = f.value; str += ((str == '') ? '' : '&') + f.name + '=' + encodeURIComponent(f.value); } } return (asObject === true) ? obj : str; }; /** * HTML string convert to DOM Elements Object * @param data * @returns {*} */ util.toNode = function (data) { var parser = new DOMParser(); var node = parser.parseFromString(data, "text/xml"); console.log(node); if (typeof node == 'object' && node.firstChild.nodeType == Node.ELEMENT_NODE) return node.firstChild; else return false; }; /** * Removes duplicate values from an array * @param arr * @returns {Array} */ util.uniqueArr = function (arr) { var tmp = []; for (var i = 0; i < arr.length; i++) { if (tmp.indexOf(arr[i]) == "-1") tmp.push(arr[i]); } return tmp; }; /** * Reads entire file into a string, synchronously * This function uses XmlHttpRequest and cannot retrieve resource from different domain. * @param url * @returns {*|string|null|string} */ util.fileGetContents = function (url) { var req = null; try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { req = new XMLHttpRequest(); } catch (e) { } } } if (req == null) throw new Error('XMLHttpRequest not supported'); req.open("GET", url, false); req.send(null); return req.responseText; }; /** * Calculates the position and size of elements. * * @param elem * @returns {{y: number, x: number, width: number, height: number}} */ util.getPosition = function (elem) { var top = 0, left = 0; if (elem.getBoundingClientRect) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return {y: Math.round(top), x: Math.round(left), width: elem.offsetWidth, height: elem.offsetHeight}; } else { //fallback to naive approach while (elem) { top = top + parseInt(elem.offsetTop, 10); left = left + parseInt(elem.offsetLeft, 10); elem = elem.offsetParent; } return {x: left, y: top, width: elem.offsetWidth, height: elem.offsetHeight}; } }; /** * Returns the coordinates of the mouse on any element * @param event * @param element * @returns {{x: number, y: number}} */ util.getMousePosition = function (event, element) { var positions = {x: 0, y: 0}; element = element || document.body; if (element instanceof HTMLElement && event instanceof MouseEvent) { if (element.getBoundingClientRect) { var rect = element.getBoundingClientRect(); positions.x = event.clientX - rect.left; positions.y = event.clientY - rect.top; } else { positions.x = event.pageX - element.offsetLeft; positions.y = event.pageY - element.offsetTop; } } return positions; }; /** * Creator of styles, return style-element or style-text. * * <pre>var style = createStyle('body','font-size:10px'); *style.add('body','font-size:10px') // added style *style.add( {'background-color':'red'} ) // added style *style.getString() // style-text *style.getObject() // style-element</pre> * * @param selector name of selector styles * @param property string "display:object" or object {'background-color':'red'} * @returns {*} return object with methods : getString(), getObject(), add() */ util.createStyle = function (selector, property) { var o = { content: '', getString: function () { return '<style rel="stylesheet">' + "\n" + o.content + "\n" + '</style>'; }, getObject: function () { var st = document.createElement('style'); st.setAttribute('rel', 'stylesheet'); st.textContent = o.content; return st; }, add: function (select, prop) { if (typeof prop === 'string') { o.content += select + "{" + ( (prop.substr(-1) == ';') ? prop : prop + ';' ) + "}"; } else if (typeof prop === 'object') { o.content += select + "{"; for (var key in prop) o.content += key + ':' + prop[key] + ';'; o.content += "}"; } return this; } }; return o.add(selector, property); }; /** * Create new NodeElement * @param tag element tag name 'p, div, h3 ... other' * @param attrs object with attributes key=value * @param inner text, html or NodeElement * @returns {Element} */ util.createElement = function (tag, attrs, inner) { var elem = document.createElement(tag); if (typeof attrs === 'object') { for (var key in attrs) elem.setAttribute(key, attrs[key]); } if (typeof inner === 'string') { elem.innerHTML = inner; } else if (typeof inner === 'object') { elem.appendChild(elem); } return elem; }; /** * Returns a random integer between min, max, if not specified the default of 0 to 100 * @param min * @param max * @returns {number} */ util.rand = function (min, max) { min = min || 0; max = max || 100; return Math.floor(Math.random() * (max - min + 1) + min); }; /** * Returns random string color, HEX format * @returns {string} */ util.randColor = function () { var letters = '0123456789ABCDEF'.split(''), color = '#'; for (var i = 0; i < 6; i++) color += letters[Math.floor(Math.random() * 16)]; return color; }; /** * Converts degrees to radians * @param deg * @returns {number} */ util.degreesToRadians = function (deg) { return (deg * Math.PI) / 180; }; /** * Converts radians to degrees * @param rad * @returns {number} */ util.radiansToDegrees = function (rad) { return (rad * 180) / Math.PI; }; /** * The calculation of the distance between points * The point is an object with properties `x` and `y` {x:100,y:100} * @param point1 * @param point2 * @returns {number} */ util.distanceBetween = function (point1, point2) { var dx = point2.x - point1.x; var dy = point2.y - point1.y; return Math.sqrt(dx * dx + dy * dy); }; /** * Encode URI params * @param data Object key=value * @returns {*} query string */ util.encodeData = function (data) { if (typeof data === 'string') return data; if (typeof data !== 'object') return ''; var convertData = []; Object.keys(data).forEach(function (key) { convertData.push(key + '=' + encodeURIComponent(data[key])); }); return convertData.join('&'); }; /** * Parse URI Request data into object * @param url * @returns {{}} */ util.parseGet = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; if (parser.search.length > 1) { parser.search.substr(1).split('&').forEach(function (part) { var item = part.split('='); params[item[0]] = decodeURIComponent(item[1]); }); } return params; }; /** * Parse Url string/location into object * @param url * @returns {{}} */ util.parseUrl = function (url) { url = url || document.location; var params = {}; var parser = document.createElement('a'); parser.href = url; params.protocol = parser.protocol; params.host = parser.host; params.hostname = parser.hostname; params.port = parser.port; params.pathname = parser.pathname; params.hash = parser.hash; params.search = parser.search; params.get = util.parseGet(parser.search); return params; }; util.each = function (data, callback) { if (util.isArr(data)) { for (var i = 0; i < data.length; i++) callback.call(null, data[i]); } else if (util.isObj(data)) { for (var k in data) callback.call(null, k, data[k]); } else return false; }; util.ucfirst = function (string) { return string && string[0].toUpperCase() + string.slice(1); }; util.node2html = function (element) { var container = document.createElement("div"); container.appendChild(element.cloneNode(true)); return container.innerHTML; }; util.html2node = function (string) { var i, fragment = document.createDocumentFragment(), container = document.createElement("div"); container.innerHTML = string; while (i = container.firstChild) fragment.appendChild(i); return fragment.childNodes.length === 1 ? fragment.firstChild : fragment; }; util.base64encode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64encoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; for (var i = 0; i < str.length;) { chr1 = str.charCodeAt(i++); chr2 = str.charCodeAt(i++); chr3 = str.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = isNaN(chr2) ? 64 : (((chr2 & 15) << 2) | (chr3 >> 6)); enc4 = isNaN(chr3) ? 64 : (chr3 & 63); b64encoded += b64chars.charAt(enc1) + b64chars.charAt(enc2) + b64chars.charAt(enc3) + b64chars.charAt(enc4); } return b64encoded; }; util.base64decode = function (str) { var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var b64decoded = ''; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; str = str.replace(/[^a-z0-9\+\/\=]/gi, ''); for (var i = 0; i < str.length;) { enc1 = b64chars.indexOf(str.charAt(i++)); enc2 = b64chars.indexOf(str.charAt(i++)); enc3 = b64chars.indexOf(str.charAt(i++)); enc4 = b64chars.indexOf(str.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; b64decoded = b64decoded + String.fromCharCode(chr1); if (enc3 < 64) { b64decoded += String.fromCharCode(chr2); } if (enc4 < 64) { b64decoded += String.fromCharCode(chr3); } } return b64decoded; }; /** * Cross-browser function for the character of the event keypress: * @param event event.type must keypress * @returns {*} */ util.getChar = function (event) { if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; }; util.Date = function () { }; util.Date.time = function (date) { "use strict"; return date instanceof Date ? date.getTime() : (new Date).getTime(); }; /** * Add days to some date * @param day number of days. 0.04 - 1 hour, 0.5 - 12 hour, 1 - 1 day * @param startDate type Date, start date * @returns {*} type Date */ util.Date.addDays = function (day, startDate) { var date = startDate ? new Date(startDate) : new Date(); date.setTime(date.getTime() + (day * 86400000)); return date; }; util.Date.daysBetween = function (date1, date2) { var ONE_DAY = 86400000, date1_ms = date1.getTime(), date2_ms = date2.getTime(); return Math.round((Math.abs(date1_ms - date2_ms)) / ONE_DAY) }; util.Storage = function (name, value) { if (!name) { return false; } else if (value === undefined) { return util.Storage.get(name); } else if (!value) { return util.Storage.remove(name); } else { return util.Storage.set(name, value); } }; util.Storage.set = function (name, value) { try { value = JSON.stringify(value) } catch (error) { } return window.localStorage.setItem(name, value); }; util.Storage.get = function (name) { var value = window.localStorage.getItem(name); if (value) try { value = JSON.parse(value) } catch (error) { } return value; }; util.Storage.remove = function (name) { return window.localStorage.removeItem(name); }; util.Storage.key = function (name) { return window.localStorage.key(key); }; // when invoked, will empty all keys out of the storage. util.Storage.clear = function () { return window.localStorage.clear(); }; // returns an integer representing the number of data items stored in the Storage object. util.Storage.length = function () { return window.localStorage.length; }; /** * возвращает cookie с именем name, если есть, если нет, то undefined * @param name * @param value */ util.Cookie = function (name, value) { "use strict"; if (value === undefined) { return util.Cookie.get(name); } else if (value === false || value === null) { util.Cookie.delete(name); } else { util.Cookie.set(name, value); } }; util.Cookie.get = function (name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; }; /** * * @param name * @param value * @param {{}} options {expires: 0, path: '/', domain: 'site.com', secure: false} * expires - ms, Date, -1, 0 */ util.Cookie.set = function (name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires == "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires * 1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for (var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; }; util.Cookie.delete = util.Cookie.remove = function (name, option) { "use strict"; option = typeof option === 'object' ? option : {}; option.expires = -1; util.Cookie.set(name, "", option); }; util.getURLParameter = function (name) { var reg = (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]; return reg === null ? undefined : decodeURI(reg); }; /** * An asynchronous for-each loop * * @param {Array} array The array to loop through * * @param {function} done Callback function (when the loop is finished or an error occurs) * * @param {function} iterator * The logic for each iteration. Signature is `function(item, index, next)`. * Call `next()` to continue to the next item. Call `next(Error)` to throw an error and cancel the loop. * Or don't call `next` at all to break out of the loop. */ util.asyncForEach = function (array, done, iterator) { var i = 0; next(); function next(err) { if (err) done(err); else if (i >= array.length) done(); else if (i < array.length) { var item = array[i++]; setTimeout(function () { iterator(item, i - 1, next); }, 0); } } }; /** * Calls the callback in a given interval until it returns true * @param {function} callback * @param {number} interval in milliseconds */ util.waitFor = function (callback, interval) { var internalCallback = function () { if (callback() !== true) { setTimeout(internalCallback, interval); } }; internalCallback(); }; /** * Remove item from array * @param item * @param stack * @returns {Array} */ util.rmInArray = function (item, stack) { var newStack = []; for (var i = 0; i < stack.length; i++) { if (stack[i] && stack[i] != item) newStack.push(stack[i]); } return newStack; }; /** * @param text * @returns {string|void|XML} */ util.toTranslit = function (text) { return text.replace(/([а-яё])|([\s_-])|([^a-z\d])/gi, function (all, ch, space, words, i) { if (space || words) return space ? '-' : ''; var code = ch.charCodeAt(0), index = code == 1025 || code == 1105 ? 0 : code > 1071 ? code - 1071 : code - 1039, t = ['yo', 'a', 'b', 'v', 'g', 'd', 'e', 'zh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shch', '', 'y', '', 'e', 'yu', 'ya']; return t[index]; }); }; window.Util = util; })(window);
{ destination[property] = source[property]; }
conditional_block
process.py
import os sys = os.system CC = 'g++ {} -std=gnu++0x -Wall' FLAG_clear = ['/c', '-c'] FLAG_window = ['/w', '-w'] FLAG_exit = ['/e', '-e'] def main(): print('List of existing <*.cpp> files:') files = [] counter = 0 for file in os.listdir(): if file[-4:] == '.cpp': counter += 1 files.append(file) print('{:->3d}) {}'.format(counter, file[:-4])) name = '' flags = [] command, *ex = input('Enter your <command> [<name>] [<*flags>]: ').split() if len(ex): name = ex[0] flags = list(ex[1:]) try: name = files[int(name) - 1] except: if name[0] == '#': try: fileid = int(name[1:]) name = files[fileid - 1] except: pass else: flags = list(ex) if command == 'open': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') if len(list(set(FLAG_window).intersection(set(flags)))) > 0: sys('start {}'.format(name)) else: sys('{}'.format(name)) elif command == 'compile': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err:
elif command == 'run': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully. Starting:\n' + '-' * 31) if len(list(set(FLAG_window).intersection(set(flags)))) > 0: err2 = sys('start {}.exe'.format(name[:-4])) else: err2 = sys('{}.exe'.format(name[:-4])) if err2: print('-' * 30 + '\nError during execution. <{}>'.format(err2)) else: print('-' * 17 + '\nDone succesfully.') elif command == 'list': if name != '': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('List of existing <*.{}> files:'.format(name)) l = len(name) for file in os.listdir(): if file[-l:] == name: print('{:>20}'.format(file[:-l - 1])) else: print('List of all existing files:') for file in os.listdir(): print('{:>20}'.format(file)) if len(list(set(FLAG_exit).intersection(set(flags)))) == 0: input('-' * 25 + '\nEnd. Press enter to exit: ') main()
print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully.')
random_line_split
process.py
import os sys = os.system CC = 'g++ {} -std=gnu++0x -Wall' FLAG_clear = ['/c', '-c'] FLAG_window = ['/w', '-w'] FLAG_exit = ['/e', '-e'] def main():
main()
print('List of existing <*.cpp> files:') files = [] counter = 0 for file in os.listdir(): if file[-4:] == '.cpp': counter += 1 files.append(file) print('{:->3d}) {}'.format(counter, file[:-4])) name = '' flags = [] command, *ex = input('Enter your <command> [<name>] [<*flags>]: ').split() if len(ex): name = ex[0] flags = list(ex[1:]) try: name = files[int(name) - 1] except: if name[0] == '#': try: fileid = int(name[1:]) name = files[fileid - 1] except: pass else: flags = list(ex) if command == 'open': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') if len(list(set(FLAG_window).intersection(set(flags)))) > 0: sys('start {}'.format(name)) else: sys('{}'.format(name)) elif command == 'compile': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully.') elif command == 'run': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully. Starting:\n' + '-' * 31) if len(list(set(FLAG_window).intersection(set(flags)))) > 0: err2 = sys('start {}.exe'.format(name[:-4])) else: err2 = sys('{}.exe'.format(name[:-4])) if err2: print('-' * 30 + '\nError during execution. <{}>'.format(err2)) else: print('-' * 17 + '\nDone succesfully.') elif command == 'list': if name != '': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('List of existing <*.{}> files:'.format(name)) l = len(name) for file in os.listdir(): if file[-l:] == name: print('{:>20}'.format(file[:-l - 1])) else: print('List of all existing files:') for file in os.listdir(): print('{:>20}'.format(file)) if len(list(set(FLAG_exit).intersection(set(flags)))) == 0: input('-' * 25 + '\nEnd. Press enter to exit: ')
identifier_body
process.py
import os sys = os.system CC = 'g++ {} -std=gnu++0x -Wall' FLAG_clear = ['/c', '-c'] FLAG_window = ['/w', '-w'] FLAG_exit = ['/e', '-e'] def
(): print('List of existing <*.cpp> files:') files = [] counter = 0 for file in os.listdir(): if file[-4:] == '.cpp': counter += 1 files.append(file) print('{:->3d}) {}'.format(counter, file[:-4])) name = '' flags = [] command, *ex = input('Enter your <command> [<name>] [<*flags>]: ').split() if len(ex): name = ex[0] flags = list(ex[1:]) try: name = files[int(name) - 1] except: if name[0] == '#': try: fileid = int(name[1:]) name = files[fileid - 1] except: pass else: flags = list(ex) if command == 'open': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') if len(list(set(FLAG_window).intersection(set(flags)))) > 0: sys('start {}'.format(name)) else: sys('{}'.format(name)) elif command == 'compile': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully.') elif command == 'run': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully. Starting:\n' + '-' * 31) if len(list(set(FLAG_window).intersection(set(flags)))) > 0: err2 = sys('start {}.exe'.format(name[:-4])) else: err2 = sys('{}.exe'.format(name[:-4])) if err2: print('-' * 30 + '\nError during execution. <{}>'.format(err2)) else: print('-' * 17 + '\nDone succesfully.') elif command == 'list': if name != '': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('List of existing <*.{}> files:'.format(name)) l = len(name) for file in os.listdir(): if file[-l:] == name: print('{:>20}'.format(file[:-l - 1])) else: print('List of all existing files:') for file in os.listdir(): print('{:>20}'.format(file)) if len(list(set(FLAG_exit).intersection(set(flags)))) == 0: input('-' * 25 + '\nEnd. Press enter to exit: ') main()
main
identifier_name
process.py
import os sys = os.system CC = 'g++ {} -std=gnu++0x -Wall' FLAG_clear = ['/c', '-c'] FLAG_window = ['/w', '-w'] FLAG_exit = ['/e', '-e'] def main(): print('List of existing <*.cpp> files:') files = [] counter = 0 for file in os.listdir(): if file[-4:] == '.cpp': counter += 1 files.append(file) print('{:->3d}) {}'.format(counter, file[:-4])) name = '' flags = [] command, *ex = input('Enter your <command> [<name>] [<*flags>]: ').split() if len(ex): name = ex[0] flags = list(ex[1:]) try: name = files[int(name) - 1] except: if name[0] == '#': try: fileid = int(name[1:]) name = files[fileid - 1] except: pass else: flags = list(ex) if command == 'open': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') if len(list(set(FLAG_window).intersection(set(flags)))) > 0: sys('start {}'.format(name)) else: sys('{}'.format(name)) elif command == 'compile': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully.') elif command == 'run': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0: sys('cls') print('Compiling...') err = sys((CC+' -o {}.exe').format(name, name[:-4])) if err: print('Error during compiling. <{}>'.format(err)) else: print('Compiled succesfully. Starting:\n' + '-' * 31) if len(list(set(FLAG_window).intersection(set(flags)))) > 0: err2 = sys('start {}.exe'.format(name[:-4])) else: err2 = sys('{}.exe'.format(name[:-4])) if err2: print('-' * 30 + '\nError during execution. <{}>'.format(err2)) else: print('-' * 17 + '\nDone succesfully.') elif command == 'list': if name != '': if len(list(set(FLAG_clear).intersection(set(flags)))) > 0:
print('List of existing <*.{}> files:'.format(name)) l = len(name) for file in os.listdir(): if file[-l:] == name: print('{:>20}'.format(file[:-l - 1])) else: print('List of all existing files:') for file in os.listdir(): print('{:>20}'.format(file)) if len(list(set(FLAG_exit).intersection(set(flags)))) == 0: input('-' * 25 + '\nEnd. Press enter to exit: ') main()
sys('cls')
conditional_block
html_diff.py
from __future__ import absolute_import from typing import Callable, Tuple, Text from django.conf import settings from diff_match_patch import diff_match_patch import platform import logging # TODO: handle changes in link hrefs def highlight_with_class(klass, text): # type: (Text, Text) -> Text return '<span class="%s">%s</span>' % (klass, text) def highlight_inserted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_inserted', text) def highlight_deleted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_deleted', text) def highlight_replaced(text): # type: (Text) -> Text return highlight_with_class('highlight_text_replaced', text) def chunkize(text, in_tag): # type: (Text, bool) -> Tuple[List[Tuple[Text, Text]], bool] start = 0 idx = 0 chunks = [] # type: List[Tuple[Text, Text]] for c in text: if c == '<': in_tag = True if start != idx: chunks.append(('text', text[start:idx])) start = idx elif c == '>': in_tag = False if start != idx + 1: chunks.append(('tag', text[start:idx + 1])) start = idx + 1 idx += 1 if start != idx: chunks.append(('tag' if in_tag else 'text', text[start:idx])) return chunks, in_tag def highlight_chunks(chunks, highlight_func): # type: (List[Tuple[Text, Text]], Callable[[Text], Text]) -> Text retval = u'' for type, text in chunks: if type == 'text': retval += highlight_func(text) else: retval += text return retval def verify_html(html): # type: (Text) -> bool # TODO: Actually parse the resulting HTML to ensure we don't # create mal-formed markup. This is unfortunately hard because # we both want pretty strict parsing and we want to parse html5 # fragments. For now, we do a basic sanity check. in_tag = False for c in html:
if in_tag: return False return True def highlight_html_differences(s1, s2): # type: (Text, Text) -> Text differ = diff_match_patch() ops = differ.diff_main(s1, s2) differ.diff_cleanupSemantic(ops) retval = u'' in_tag = False idx = 0 while idx < len(ops): op, text = ops[idx] next_op = None if idx != len(ops) - 1: next_op, next_text = ops[idx + 1] if op == diff_match_patch.DIFF_DELETE and next_op == diff_match_patch.DIFF_INSERT: # Replace operation chunks, in_tag = chunkize(next_text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_INSERT and next_op == diff_match_patch.DIFF_DELETE: # Replace operation # I have no idea whether diff_match_patch generates inserts followed # by deletes, but it doesn't hurt to handle them chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_DELETE: retval += highlight_deleted('&nbsp;') elif op == diff_match_patch.DIFF_INSERT: chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_inserted) elif op == diff_match_patch.DIFF_EQUAL: chunks, in_tag = chunkize(text, in_tag) retval += text idx += 1 if not verify_html(retval): from zerver.lib.actions import internal_send_message # We probably want more information here logging.getLogger('').error('HTML diff produced mal-formed HTML') if settings.ERROR_BOT is not None: subject = "HTML diff failure on %s" % (platform.node(),) internal_send_message(settings.ERROR_BOT, "stream", "errors", subject, "HTML diff produced malformed HTML") return s2 return retval
if c == '<': if in_tag: return False in_tag = True elif c == '>': if not in_tag: return False in_tag = False
conditional_block
html_diff.py
from __future__ import absolute_import from typing import Callable, Tuple, Text from django.conf import settings from diff_match_patch import diff_match_patch import platform import logging # TODO: handle changes in link hrefs def highlight_with_class(klass, text): # type: (Text, Text) -> Text return '<span class="%s">%s</span>' % (klass, text) def highlight_inserted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_inserted', text) def highlight_deleted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_deleted', text) def highlight_replaced(text): # type: (Text) -> Text return highlight_with_class('highlight_text_replaced', text) def chunkize(text, in_tag): # type: (Text, bool) -> Tuple[List[Tuple[Text, Text]], bool] start = 0 idx = 0 chunks = [] # type: List[Tuple[Text, Text]] for c in text: if c == '<': in_tag = True if start != idx: chunks.append(('text', text[start:idx])) start = idx elif c == '>': in_tag = False if start != idx + 1: chunks.append(('tag', text[start:idx + 1])) start = idx + 1 idx += 1 if start != idx: chunks.append(('tag' if in_tag else 'text', text[start:idx])) return chunks, in_tag def highlight_chunks(chunks, highlight_func):
for type, text in chunks: if type == 'text': retval += highlight_func(text) else: retval += text return retval def verify_html(html): # type: (Text) -> bool # TODO: Actually parse the resulting HTML to ensure we don't # create mal-formed markup. This is unfortunately hard because # we both want pretty strict parsing and we want to parse html5 # fragments. For now, we do a basic sanity check. in_tag = False for c in html: if c == '<': if in_tag: return False in_tag = True elif c == '>': if not in_tag: return False in_tag = False if in_tag: return False return True def highlight_html_differences(s1, s2): # type: (Text, Text) -> Text differ = diff_match_patch() ops = differ.diff_main(s1, s2) differ.diff_cleanupSemantic(ops) retval = u'' in_tag = False idx = 0 while idx < len(ops): op, text = ops[idx] next_op = None if idx != len(ops) - 1: next_op, next_text = ops[idx + 1] if op == diff_match_patch.DIFF_DELETE and next_op == diff_match_patch.DIFF_INSERT: # Replace operation chunks, in_tag = chunkize(next_text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_INSERT and next_op == diff_match_patch.DIFF_DELETE: # Replace operation # I have no idea whether diff_match_patch generates inserts followed # by deletes, but it doesn't hurt to handle them chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_DELETE: retval += highlight_deleted('&nbsp;') elif op == diff_match_patch.DIFF_INSERT: chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_inserted) elif op == diff_match_patch.DIFF_EQUAL: chunks, in_tag = chunkize(text, in_tag) retval += text idx += 1 if not verify_html(retval): from zerver.lib.actions import internal_send_message # We probably want more information here logging.getLogger('').error('HTML diff produced mal-formed HTML') if settings.ERROR_BOT is not None: subject = "HTML diff failure on %s" % (platform.node(),) internal_send_message(settings.ERROR_BOT, "stream", "errors", subject, "HTML diff produced malformed HTML") return s2 return retval
# type: (List[Tuple[Text, Text]], Callable[[Text], Text]) -> Text retval = u''
random_line_split
html_diff.py
from __future__ import absolute_import from typing import Callable, Tuple, Text from django.conf import settings from diff_match_patch import diff_match_patch import platform import logging # TODO: handle changes in link hrefs def highlight_with_class(klass, text): # type: (Text, Text) -> Text return '<span class="%s">%s</span>' % (klass, text) def highlight_inserted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_inserted', text) def highlight_deleted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_deleted', text) def highlight_replaced(text): # type: (Text) -> Text return highlight_with_class('highlight_text_replaced', text) def
(text, in_tag): # type: (Text, bool) -> Tuple[List[Tuple[Text, Text]], bool] start = 0 idx = 0 chunks = [] # type: List[Tuple[Text, Text]] for c in text: if c == '<': in_tag = True if start != idx: chunks.append(('text', text[start:idx])) start = idx elif c == '>': in_tag = False if start != idx + 1: chunks.append(('tag', text[start:idx + 1])) start = idx + 1 idx += 1 if start != idx: chunks.append(('tag' if in_tag else 'text', text[start:idx])) return chunks, in_tag def highlight_chunks(chunks, highlight_func): # type: (List[Tuple[Text, Text]], Callable[[Text], Text]) -> Text retval = u'' for type, text in chunks: if type == 'text': retval += highlight_func(text) else: retval += text return retval def verify_html(html): # type: (Text) -> bool # TODO: Actually parse the resulting HTML to ensure we don't # create mal-formed markup. This is unfortunately hard because # we both want pretty strict parsing and we want to parse html5 # fragments. For now, we do a basic sanity check. in_tag = False for c in html: if c == '<': if in_tag: return False in_tag = True elif c == '>': if not in_tag: return False in_tag = False if in_tag: return False return True def highlight_html_differences(s1, s2): # type: (Text, Text) -> Text differ = diff_match_patch() ops = differ.diff_main(s1, s2) differ.diff_cleanupSemantic(ops) retval = u'' in_tag = False idx = 0 while idx < len(ops): op, text = ops[idx] next_op = None if idx != len(ops) - 1: next_op, next_text = ops[idx + 1] if op == diff_match_patch.DIFF_DELETE and next_op == diff_match_patch.DIFF_INSERT: # Replace operation chunks, in_tag = chunkize(next_text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_INSERT and next_op == diff_match_patch.DIFF_DELETE: # Replace operation # I have no idea whether diff_match_patch generates inserts followed # by deletes, but it doesn't hurt to handle them chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_DELETE: retval += highlight_deleted('&nbsp;') elif op == diff_match_patch.DIFF_INSERT: chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_inserted) elif op == diff_match_patch.DIFF_EQUAL: chunks, in_tag = chunkize(text, in_tag) retval += text idx += 1 if not verify_html(retval): from zerver.lib.actions import internal_send_message # We probably want more information here logging.getLogger('').error('HTML diff produced mal-formed HTML') if settings.ERROR_BOT is not None: subject = "HTML diff failure on %s" % (platform.node(),) internal_send_message(settings.ERROR_BOT, "stream", "errors", subject, "HTML diff produced malformed HTML") return s2 return retval
chunkize
identifier_name
html_diff.py
from __future__ import absolute_import from typing import Callable, Tuple, Text from django.conf import settings from diff_match_patch import diff_match_patch import platform import logging # TODO: handle changes in link hrefs def highlight_with_class(klass, text): # type: (Text, Text) -> Text
def highlight_inserted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_inserted', text) def highlight_deleted(text): # type: (Text) -> Text return highlight_with_class('highlight_text_deleted', text) def highlight_replaced(text): # type: (Text) -> Text return highlight_with_class('highlight_text_replaced', text) def chunkize(text, in_tag): # type: (Text, bool) -> Tuple[List[Tuple[Text, Text]], bool] start = 0 idx = 0 chunks = [] # type: List[Tuple[Text, Text]] for c in text: if c == '<': in_tag = True if start != idx: chunks.append(('text', text[start:idx])) start = idx elif c == '>': in_tag = False if start != idx + 1: chunks.append(('tag', text[start:idx + 1])) start = idx + 1 idx += 1 if start != idx: chunks.append(('tag' if in_tag else 'text', text[start:idx])) return chunks, in_tag def highlight_chunks(chunks, highlight_func): # type: (List[Tuple[Text, Text]], Callable[[Text], Text]) -> Text retval = u'' for type, text in chunks: if type == 'text': retval += highlight_func(text) else: retval += text return retval def verify_html(html): # type: (Text) -> bool # TODO: Actually parse the resulting HTML to ensure we don't # create mal-formed markup. This is unfortunately hard because # we both want pretty strict parsing and we want to parse html5 # fragments. For now, we do a basic sanity check. in_tag = False for c in html: if c == '<': if in_tag: return False in_tag = True elif c == '>': if not in_tag: return False in_tag = False if in_tag: return False return True def highlight_html_differences(s1, s2): # type: (Text, Text) -> Text differ = diff_match_patch() ops = differ.diff_main(s1, s2) differ.diff_cleanupSemantic(ops) retval = u'' in_tag = False idx = 0 while idx < len(ops): op, text = ops[idx] next_op = None if idx != len(ops) - 1: next_op, next_text = ops[idx + 1] if op == diff_match_patch.DIFF_DELETE and next_op == diff_match_patch.DIFF_INSERT: # Replace operation chunks, in_tag = chunkize(next_text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_INSERT and next_op == diff_match_patch.DIFF_DELETE: # Replace operation # I have no idea whether diff_match_patch generates inserts followed # by deletes, but it doesn't hurt to handle them chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_replaced) idx += 1 elif op == diff_match_patch.DIFF_DELETE: retval += highlight_deleted('&nbsp;') elif op == diff_match_patch.DIFF_INSERT: chunks, in_tag = chunkize(text, in_tag) retval += highlight_chunks(chunks, highlight_inserted) elif op == diff_match_patch.DIFF_EQUAL: chunks, in_tag = chunkize(text, in_tag) retval += text idx += 1 if not verify_html(retval): from zerver.lib.actions import internal_send_message # We probably want more information here logging.getLogger('').error('HTML diff produced mal-formed HTML') if settings.ERROR_BOT is not None: subject = "HTML diff failure on %s" % (platform.node(),) internal_send_message(settings.ERROR_BOT, "stream", "errors", subject, "HTML diff produced malformed HTML") return s2 return retval
return '<span class="%s">%s</span>' % (klass, text)
identifier_body
request.spec.browser.ts
/* * Copyright (c) 2019 by Filestack. * Some rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.
import { FsRequest } from './request'; import { FsHttpMethod } from './types'; import { Dispatch } from './dispatch'; jest.mock('./dispatch'); const dispatchSpy = jest.fn(() => Promise.resolve('response')); // @ts-ignore Dispatch.prototype.request.mockImplementation(dispatchSpy); describe('Request/Request', () => { describe('dispatch', () => { it('should return response', async () => { const fsRequest = new FsRequest(); const response = await fsRequest.dispatch({ method: FsHttpMethod.GET }); expect(dispatchSpy).toHaveBeenCalledWith({ method: FsHttpMethod.GET }); expect(response).toBe('response'); }); }); });
*/
random_line_split
main.rs
extern crate itertools; use std::ops::Add; use itertools::Itertools; struct Character { hitpoints: u16, damage: u16, armor: u16 } impl Character { fn rounds(&self, opponent: &Character) -> u16 { let round_damage: f64 = if opponent.armor >= self.damage { 1 } else { self.damage - opponent.armor } as f64; ((opponent.hitpoints as f64) / round_damage).ceil() as u16 } fn beats(&self, opponent: &Character) -> bool { let a = self.rounds(opponent); let b = opponent.rounds(&self); a <= b } } #[derive(Clone)] struct Inventory { cost: u16, damage: u16, armor: u16 } impl<'a, 'b> Add<&'b Inventory> for &'a Inventory { type Output = Inventory; fn add(self, other: &'b Inventory) -> Inventory { Inventory { cost: self.cost + other.cost, damage: self.damage + other.damage, armor: self.armor + other.armor } } } fn main() { let weapons = [ Inventory { cost: 8, damage: 4, armor: 0 }, Inventory { cost: 10, damage: 5, armor: 0 }, Inventory { cost: 25, damage: 6, armor: 0 }, Inventory { cost: 40, damage: 7, armor: 0 }, Inventory { cost: 74, damage: 8, armor: 0 }, ]; let armor = [ Inventory { cost: 13, damage: 0, armor: 1 }, Inventory { cost: 31, damage: 0, armor: 2 }, Inventory { cost: 53, damage: 0, armor: 3 }, Inventory { cost: 75, damage: 0, armor: 4 }, Inventory { cost: 102, damage: 0, armor: 5 }, ]; let rings = [ Inventory { cost: 25, damage: 1, armor: 0 }, Inventory { cost: 50, damage: 2, armor: 0 }, Inventory { cost: 100, damage: 3, armor: 0 }, Inventory { cost: 20, damage: 0, armor: 1 }, Inventory { cost: 40, damage: 0, armor: 2 }, Inventory { cost: 80, damage: 0, armor: 3 }, ]; let boss = Character { hitpoints: 104, damage: 8, armor: 1 }; let mut minimal_inventory = Inventory { cost: u16::max_value(), damage: 0, armor: 0 }; let mut maximal_inventory = Inventory { cost: 0, damage: 0, armor: 0 }; for weapon in &weapons { let mut inventories = Vec::new(); inventories.push(weapon.clone()); for armor in &armor { inventories.push(weapon + armor); }
for inventory in inventories.iter() { additional.push(inventory + &rings.0); additional.push(inventory + &rings.1); additional.push(inventory + &(rings.0 + rings.1)); } } inventories.extend(additional); for inventory in &inventories { let player = Character { hitpoints: 100, damage: inventory.damage, armor: inventory.armor }; let winner = player.beats(&boss); if winner && inventory.cost < minimal_inventory.cost { minimal_inventory = inventory.clone(); } else if !winner && inventory.cost > maximal_inventory.cost { maximal_inventory = inventory.clone(); } } } println!("Uncle Scrooge wins by spending merely {} bucks.", minimal_inventory.cost); println!("Betrayed by the shopkeeper, he pays {} bucks and loses.", maximal_inventory.cost); }
let mut additional = Vec::with_capacity(rings.len() * 3); for rings in rings.iter().combinations() {
random_line_split
main.rs
extern crate itertools; use std::ops::Add; use itertools::Itertools; struct Character { hitpoints: u16, damage: u16, armor: u16 } impl Character { fn rounds(&self, opponent: &Character) -> u16 { let round_damage: f64 = if opponent.armor >= self.damage { 1 } else
as f64; ((opponent.hitpoints as f64) / round_damage).ceil() as u16 } fn beats(&self, opponent: &Character) -> bool { let a = self.rounds(opponent); let b = opponent.rounds(&self); a <= b } } #[derive(Clone)] struct Inventory { cost: u16, damage: u16, armor: u16 } impl<'a, 'b> Add<&'b Inventory> for &'a Inventory { type Output = Inventory; fn add(self, other: &'b Inventory) -> Inventory { Inventory { cost: self.cost + other.cost, damage: self.damage + other.damage, armor: self.armor + other.armor } } } fn main() { let weapons = [ Inventory { cost: 8, damage: 4, armor: 0 }, Inventory { cost: 10, damage: 5, armor: 0 }, Inventory { cost: 25, damage: 6, armor: 0 }, Inventory { cost: 40, damage: 7, armor: 0 }, Inventory { cost: 74, damage: 8, armor: 0 }, ]; let armor = [ Inventory { cost: 13, damage: 0, armor: 1 }, Inventory { cost: 31, damage: 0, armor: 2 }, Inventory { cost: 53, damage: 0, armor: 3 }, Inventory { cost: 75, damage: 0, armor: 4 }, Inventory { cost: 102, damage: 0, armor: 5 }, ]; let rings = [ Inventory { cost: 25, damage: 1, armor: 0 }, Inventory { cost: 50, damage: 2, armor: 0 }, Inventory { cost: 100, damage: 3, armor: 0 }, Inventory { cost: 20, damage: 0, armor: 1 }, Inventory { cost: 40, damage: 0, armor: 2 }, Inventory { cost: 80, damage: 0, armor: 3 }, ]; let boss = Character { hitpoints: 104, damage: 8, armor: 1 }; let mut minimal_inventory = Inventory { cost: u16::max_value(), damage: 0, armor: 0 }; let mut maximal_inventory = Inventory { cost: 0, damage: 0, armor: 0 }; for weapon in &weapons { let mut inventories = Vec::new(); inventories.push(weapon.clone()); for armor in &armor { inventories.push(weapon + armor); } let mut additional = Vec::with_capacity(rings.len() * 3); for rings in rings.iter().combinations() { for inventory in inventories.iter() { additional.push(inventory + &rings.0); additional.push(inventory + &rings.1); additional.push(inventory + &(rings.0 + rings.1)); } } inventories.extend(additional); for inventory in &inventories { let player = Character { hitpoints: 100, damage: inventory.damage, armor: inventory.armor }; let winner = player.beats(&boss); if winner && inventory.cost < minimal_inventory.cost { minimal_inventory = inventory.clone(); } else if !winner && inventory.cost > maximal_inventory.cost { maximal_inventory = inventory.clone(); } } } println!("Uncle Scrooge wins by spending merely {} bucks.", minimal_inventory.cost); println!("Betrayed by the shopkeeper, he pays {} bucks and loses.", maximal_inventory.cost); }
{ self.damage - opponent.armor }
conditional_block
main.rs
extern crate itertools; use std::ops::Add; use itertools::Itertools; struct
{ hitpoints: u16, damage: u16, armor: u16 } impl Character { fn rounds(&self, opponent: &Character) -> u16 { let round_damage: f64 = if opponent.armor >= self.damage { 1 } else { self.damage - opponent.armor } as f64; ((opponent.hitpoints as f64) / round_damage).ceil() as u16 } fn beats(&self, opponent: &Character) -> bool { let a = self.rounds(opponent); let b = opponent.rounds(&self); a <= b } } #[derive(Clone)] struct Inventory { cost: u16, damage: u16, armor: u16 } impl<'a, 'b> Add<&'b Inventory> for &'a Inventory { type Output = Inventory; fn add(self, other: &'b Inventory) -> Inventory { Inventory { cost: self.cost + other.cost, damage: self.damage + other.damage, armor: self.armor + other.armor } } } fn main() { let weapons = [ Inventory { cost: 8, damage: 4, armor: 0 }, Inventory { cost: 10, damage: 5, armor: 0 }, Inventory { cost: 25, damage: 6, armor: 0 }, Inventory { cost: 40, damage: 7, armor: 0 }, Inventory { cost: 74, damage: 8, armor: 0 }, ]; let armor = [ Inventory { cost: 13, damage: 0, armor: 1 }, Inventory { cost: 31, damage: 0, armor: 2 }, Inventory { cost: 53, damage: 0, armor: 3 }, Inventory { cost: 75, damage: 0, armor: 4 }, Inventory { cost: 102, damage: 0, armor: 5 }, ]; let rings = [ Inventory { cost: 25, damage: 1, armor: 0 }, Inventory { cost: 50, damage: 2, armor: 0 }, Inventory { cost: 100, damage: 3, armor: 0 }, Inventory { cost: 20, damage: 0, armor: 1 }, Inventory { cost: 40, damage: 0, armor: 2 }, Inventory { cost: 80, damage: 0, armor: 3 }, ]; let boss = Character { hitpoints: 104, damage: 8, armor: 1 }; let mut minimal_inventory = Inventory { cost: u16::max_value(), damage: 0, armor: 0 }; let mut maximal_inventory = Inventory { cost: 0, damage: 0, armor: 0 }; for weapon in &weapons { let mut inventories = Vec::new(); inventories.push(weapon.clone()); for armor in &armor { inventories.push(weapon + armor); } let mut additional = Vec::with_capacity(rings.len() * 3); for rings in rings.iter().combinations() { for inventory in inventories.iter() { additional.push(inventory + &rings.0); additional.push(inventory + &rings.1); additional.push(inventory + &(rings.0 + rings.1)); } } inventories.extend(additional); for inventory in &inventories { let player = Character { hitpoints: 100, damage: inventory.damage, armor: inventory.armor }; let winner = player.beats(&boss); if winner && inventory.cost < minimal_inventory.cost { minimal_inventory = inventory.clone(); } else if !winner && inventory.cost > maximal_inventory.cost { maximal_inventory = inventory.clone(); } } } println!("Uncle Scrooge wins by spending merely {} bucks.", minimal_inventory.cost); println!("Betrayed by the shopkeeper, he pays {} bucks and loses.", maximal_inventory.cost); }
Character
identifier_name
adjust_seasons_test.py
# test seasonal.adjust_seasons() options handling # # adjust_seasons() handles a variety of optional arguments. # verify that adjust_trend() correctly calledfor different option combinations. # # No noise in this test set. # from __future__ import division import numpy as np from seasonal import fit_trend, adjust_seasons # pylint:disable=import-error from seasonal.sequences import sine # pylint:disable=import-error PERIOD = 25 CYCLES = 4 AMP = 1.0 TREND = AMP / PERIOD LEVEL = 1000.0 SEASONS = sine(AMP, PERIOD, 1) DATA = LEVEL + np.arange(PERIOD * CYCLES) * TREND + np.tile(SEASONS, CYCLES) ZEROS = np.zeros(PERIOD * CYCLES) def iszero(a): return np.all(np.isclose(a, ZEROS)) def isseasons(a): return np.all(np.isclose(a, SEASONS)) def test_auto():
def test_trend_line(): adjusted = adjust_seasons(DATA, trend="line") assert adjusted.std() < DATA.std() def test_explicit_trend(): trend = fit_trend(DATA, kind="line") adjusted = adjust_seasons(DATA, trend=trend) assert adjusted.std() < DATA.std() def test_trend_period(): adjusted = adjust_seasons(DATA, trend="line", period=PERIOD) assert adjusted.std() < DATA.std() def test_trend_seasons(): adjusted = adjust_seasons(DATA, trend="line", seasons=SEASONS) assert adjusted.std() < DATA.std() def test_trend_spline(): adjusted = adjust_seasons(DATA, trend="spline") assert adjusted.std() < DATA.std() def test_period(): adjusted = adjust_seasons(DATA, period=PERIOD) assert adjusted.std() < DATA.std() adjusted = adjust_seasons(DATA, period=PERIOD // 2) # no seasonality assert adjusted is None def test_seasons(): adjusted = adjust_seasons(DATA, seasons=SEASONS) assert adjusted.std() < DATA.std()
adjusted = adjust_seasons(DATA) assert adjusted.std() < DATA.std()
identifier_body
adjust_seasons_test.py
# test seasonal.adjust_seasons() options handling # # adjust_seasons() handles a variety of optional arguments. # verify that adjust_trend() correctly calledfor different option combinations. # # No noise in this test set. # from __future__ import division import numpy as np from seasonal import fit_trend, adjust_seasons # pylint:disable=import-error from seasonal.sequences import sine # pylint:disable=import-error PERIOD = 25 CYCLES = 4 AMP = 1.0 TREND = AMP / PERIOD LEVEL = 1000.0 SEASONS = sine(AMP, PERIOD, 1) DATA = LEVEL + np.arange(PERIOD * CYCLES) * TREND + np.tile(SEASONS, CYCLES) ZEROS = np.zeros(PERIOD * CYCLES) def iszero(a): return np.all(np.isclose(a, ZEROS)) def isseasons(a): return np.all(np.isclose(a, SEASONS)) def test_auto(): adjusted = adjust_seasons(DATA) assert adjusted.std() < DATA.std() def test_trend_line(): adjusted = adjust_seasons(DATA, trend="line") assert adjusted.std() < DATA.std() def test_explicit_trend(): trend = fit_trend(DATA, kind="line") adjusted = adjust_seasons(DATA, trend=trend) assert adjusted.std() < DATA.std() def test_trend_period(): adjusted = adjust_seasons(DATA, trend="line", period=PERIOD) assert adjusted.std() < DATA.std() def test_trend_seasons(): adjusted = adjust_seasons(DATA, trend="line", seasons=SEASONS) assert adjusted.std() < DATA.std() def test_trend_spline(): adjusted = adjust_seasons(DATA, trend="spline") assert adjusted.std() < DATA.std() def test_period(): adjusted = adjust_seasons(DATA, period=PERIOD)
adjusted = adjust_seasons(DATA, period=PERIOD // 2) # no seasonality assert adjusted is None def test_seasons(): adjusted = adjust_seasons(DATA, seasons=SEASONS) assert adjusted.std() < DATA.std()
assert adjusted.std() < DATA.std()
random_line_split
adjust_seasons_test.py
# test seasonal.adjust_seasons() options handling # # adjust_seasons() handles a variety of optional arguments. # verify that adjust_trend() correctly calledfor different option combinations. # # No noise in this test set. # from __future__ import division import numpy as np from seasonal import fit_trend, adjust_seasons # pylint:disable=import-error from seasonal.sequences import sine # pylint:disable=import-error PERIOD = 25 CYCLES = 4 AMP = 1.0 TREND = AMP / PERIOD LEVEL = 1000.0 SEASONS = sine(AMP, PERIOD, 1) DATA = LEVEL + np.arange(PERIOD * CYCLES) * TREND + np.tile(SEASONS, CYCLES) ZEROS = np.zeros(PERIOD * CYCLES) def iszero(a): return np.all(np.isclose(a, ZEROS)) def isseasons(a): return np.all(np.isclose(a, SEASONS)) def test_auto(): adjusted = adjust_seasons(DATA) assert adjusted.std() < DATA.std() def test_trend_line(): adjusted = adjust_seasons(DATA, trend="line") assert adjusted.std() < DATA.std() def test_explicit_trend(): trend = fit_trend(DATA, kind="line") adjusted = adjust_seasons(DATA, trend=trend) assert adjusted.std() < DATA.std() def test_trend_period(): adjusted = adjust_seasons(DATA, trend="line", period=PERIOD) assert adjusted.std() < DATA.std() def test_trend_seasons(): adjusted = adjust_seasons(DATA, trend="line", seasons=SEASONS) assert adjusted.std() < DATA.std() def test_trend_spline(): adjusted = adjust_seasons(DATA, trend="spline") assert adjusted.std() < DATA.std() def
(): adjusted = adjust_seasons(DATA, period=PERIOD) assert adjusted.std() < DATA.std() adjusted = adjust_seasons(DATA, period=PERIOD // 2) # no seasonality assert adjusted is None def test_seasons(): adjusted = adjust_seasons(DATA, seasons=SEASONS) assert adjusted.std() < DATA.std()
test_period
identifier_name
lib.rs
// Copyright 2021 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 // // https://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. #![no_std] #![cfg_attr(feature = "allocator_api", feature(allocator_api))] #![cfg_attr(feature = "allocator_api", feature(nonnull_slice_from_raw_parts))] #[cfg(test)] #[macro_use] extern crate std; use scudo_sys::{scudo_allocate, scudo_deallocate, scudo_print_stats, SCUDO_MIN_ALIGN}; use core::alloc::{GlobalAlloc, Layout}; use core::cmp::max; /// Zero sized type representing the global static scudo allocator declared in C. #[derive(Clone, Copy)] pub struct GlobalScudoAllocator; /// Returns `layout` or the minimum size/align layout for scudo if its too small. fn fit_layout(layout: Layout) -> Layout { // SAFETY: SCUDO_MIN_ALIGN is constant and known to be powers of 2. let min_align = unsafe { SCUDO_MIN_ALIGN } as usize; let align = max(min_align, layout.align()); // SAFETY: Size and align are good by construction. unsafe { Layout::from_size_align_unchecked(layout.size(), align) } } unsafe impl GlobalAlloc for GlobalScudoAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let layout = fit_layout(layout); scudo_allocate(layout.size(), layout.align()) as _ } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr as _, layout.size(), layout.align()); } } impl GlobalScudoAllocator { /// Prints the global Scudo allocator's internal statistics.
#[cfg(feature = "allocator_api")] use core::alloc::AllocError; #[cfg(feature = "allocator_api")] use core::ptr::NonNull; #[cfg(feature = "allocator_api")] unsafe impl core::alloc::Allocator for GlobalScudoAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = fit_layout(layout); // TODO(cneo): Scudo buckets and therefore overallocates. Use SizeClassMap to // return the correct length for the slice? let ptr = unsafe { scudo_allocate(layout.size(), layout.align()) } as _; let n = NonNull::new(ptr).ok_or(AllocError)?; Ok(NonNull::slice_from_raw_parts(n, layout.size())) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr.as_ptr() as _, layout.size(), layout.align()); } } #[cfg(test)] pub mod test { use super::*; use std::prelude::v1::*; use core::alloc::Layout; use libc::{c_ulong, c_void, size_t}; use scudo_sys::{scudo_disable, scudo_enable, scudo_iterate}; extern "C" fn contains(_address: c_ulong, size: size_t, pair: *mut c_void) { let (target_size, count) = unsafe { &mut *(pair as *mut (usize, usize)) }; if size == *target_size { *count += 1; } } /// Test-only function that returns the number of allocations of a given size. fn count_allocations_by_size(size: usize) -> usize { let mut size_and_count = (size, 0usize); unsafe { scudo_disable(); scudo_iterate( contains, &mut size_and_count as *mut (usize, usize) as *mut c_void, ); scudo_enable(); } size_and_count.1 } #[test] fn test_alloc_and_dealloc_use_scudo() { let a = GlobalScudoAllocator; let layout = Layout::from_size_align(4242, 16).unwrap(); assert_eq!(count_allocations_by_size(4242), 0); let p = unsafe { a.alloc(layout) }; assert_eq!(count_allocations_by_size(4242), 1); unsafe { a.dealloc(p, layout) }; assert_eq!(count_allocations_by_size(4242), 0); } #[global_allocator] static A: GlobalScudoAllocator = GlobalScudoAllocator; #[test] fn test_vec_uses_scudo() { assert_eq!(count_allocations_by_size(8200_1337), 0); let mut v = vec![8u8; 8200_1337]; assert_eq!(count_allocations_by_size(8200_1337), 1); v.clear(); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_1337), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_vec_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(8200_4242), 0); let mut v = Vec::<u8, GlobalScudoAllocator>::with_capacity_in(8200_4242, A); assert_eq!(count_allocations_by_size(8200_4242), 1); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_4242), 0); } #[test] fn test_box_uses_scudo() { assert_eq!(count_allocations_by_size(20), 0); let b = Box::new([3.0f32; 5]); assert_eq!(count_allocations_by_size(20), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(20), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_box_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(28), 0); let b = Box::new_in([3.0f32; 7], A); assert_eq!(count_allocations_by_size(28), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(28), 0); } #[test] fn test_1byte_box_uses_scudo() { // Unlike the other arbitrary size allocations, it seems // Rust's test harness does have some 1 byte allocations so we cannot // assert there are 0, then 1, then 0. let before = count_allocations_by_size(1); let b = Box::new(1i8); assert_eq!(count_allocations_by_size(1), before + 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(1), before); } }
pub fn print_stats() { unsafe { scudo_print_stats() } } }
random_line_split
lib.rs
// Copyright 2021 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 // // https://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. #![no_std] #![cfg_attr(feature = "allocator_api", feature(allocator_api))] #![cfg_attr(feature = "allocator_api", feature(nonnull_slice_from_raw_parts))] #[cfg(test)] #[macro_use] extern crate std; use scudo_sys::{scudo_allocate, scudo_deallocate, scudo_print_stats, SCUDO_MIN_ALIGN}; use core::alloc::{GlobalAlloc, Layout}; use core::cmp::max; /// Zero sized type representing the global static scudo allocator declared in C. #[derive(Clone, Copy)] pub struct GlobalScudoAllocator; /// Returns `layout` or the minimum size/align layout for scudo if its too small. fn fit_layout(layout: Layout) -> Layout { // SAFETY: SCUDO_MIN_ALIGN is constant and known to be powers of 2. let min_align = unsafe { SCUDO_MIN_ALIGN } as usize; let align = max(min_align, layout.align()); // SAFETY: Size and align are good by construction. unsafe { Layout::from_size_align_unchecked(layout.size(), align) } } unsafe impl GlobalAlloc for GlobalScudoAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let layout = fit_layout(layout); scudo_allocate(layout.size(), layout.align()) as _ } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr as _, layout.size(), layout.align()); } } impl GlobalScudoAllocator { /// Prints the global Scudo allocator's internal statistics. pub fn print_stats() { unsafe { scudo_print_stats() } } } #[cfg(feature = "allocator_api")] use core::alloc::AllocError; #[cfg(feature = "allocator_api")] use core::ptr::NonNull; #[cfg(feature = "allocator_api")] unsafe impl core::alloc::Allocator for GlobalScudoAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = fit_layout(layout); // TODO(cneo): Scudo buckets and therefore overallocates. Use SizeClassMap to // return the correct length for the slice? let ptr = unsafe { scudo_allocate(layout.size(), layout.align()) } as _; let n = NonNull::new(ptr).ok_or(AllocError)?; Ok(NonNull::slice_from_raw_parts(n, layout.size())) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr.as_ptr() as _, layout.size(), layout.align()); } } #[cfg(test)] pub mod test { use super::*; use std::prelude::v1::*; use core::alloc::Layout; use libc::{c_ulong, c_void, size_t}; use scudo_sys::{scudo_disable, scudo_enable, scudo_iterate}; extern "C" fn contains(_address: c_ulong, size: size_t, pair: *mut c_void) { let (target_size, count) = unsafe { &mut *(pair as *mut (usize, usize)) }; if size == *target_size { *count += 1; } } /// Test-only function that returns the number of allocations of a given size. fn count_allocations_by_size(size: usize) -> usize { let mut size_and_count = (size, 0usize); unsafe { scudo_disable(); scudo_iterate( contains, &mut size_and_count as *mut (usize, usize) as *mut c_void, ); scudo_enable(); } size_and_count.1 } #[test] fn test_alloc_and_dealloc_use_scudo() { let a = GlobalScudoAllocator; let layout = Layout::from_size_align(4242, 16).unwrap(); assert_eq!(count_allocations_by_size(4242), 0); let p = unsafe { a.alloc(layout) }; assert_eq!(count_allocations_by_size(4242), 1); unsafe { a.dealloc(p, layout) }; assert_eq!(count_allocations_by_size(4242), 0); } #[global_allocator] static A: GlobalScudoAllocator = GlobalScudoAllocator; #[test] fn test_vec_uses_scudo() { assert_eq!(count_allocations_by_size(8200_1337), 0); let mut v = vec![8u8; 8200_1337]; assert_eq!(count_allocations_by_size(8200_1337), 1); v.clear(); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_1337), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_vec_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(8200_4242), 0); let mut v = Vec::<u8, GlobalScudoAllocator>::with_capacity_in(8200_4242, A); assert_eq!(count_allocations_by_size(8200_4242), 1); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_4242), 0); } #[test] fn test_box_uses_scudo() { assert_eq!(count_allocations_by_size(20), 0); let b = Box::new([3.0f32; 5]); assert_eq!(count_allocations_by_size(20), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(20), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_box_with_custom_allocator_uses_scudo()
#[test] fn test_1byte_box_uses_scudo() { // Unlike the other arbitrary size allocations, it seems // Rust's test harness does have some 1 byte allocations so we cannot // assert there are 0, then 1, then 0. let before = count_allocations_by_size(1); let b = Box::new(1i8); assert_eq!(count_allocations_by_size(1), before + 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(1), before); } }
{ assert_eq!(count_allocations_by_size(28), 0); let b = Box::new_in([3.0f32; 7], A); assert_eq!(count_allocations_by_size(28), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(28), 0); }
identifier_body
lib.rs
// Copyright 2021 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 // // https://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. #![no_std] #![cfg_attr(feature = "allocator_api", feature(allocator_api))] #![cfg_attr(feature = "allocator_api", feature(nonnull_slice_from_raw_parts))] #[cfg(test)] #[macro_use] extern crate std; use scudo_sys::{scudo_allocate, scudo_deallocate, scudo_print_stats, SCUDO_MIN_ALIGN}; use core::alloc::{GlobalAlloc, Layout}; use core::cmp::max; /// Zero sized type representing the global static scudo allocator declared in C. #[derive(Clone, Copy)] pub struct GlobalScudoAllocator; /// Returns `layout` or the minimum size/align layout for scudo if its too small. fn fit_layout(layout: Layout) -> Layout { // SAFETY: SCUDO_MIN_ALIGN is constant and known to be powers of 2. let min_align = unsafe { SCUDO_MIN_ALIGN } as usize; let align = max(min_align, layout.align()); // SAFETY: Size and align are good by construction. unsafe { Layout::from_size_align_unchecked(layout.size(), align) } } unsafe impl GlobalAlloc for GlobalScudoAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let layout = fit_layout(layout); scudo_allocate(layout.size(), layout.align()) as _ } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr as _, layout.size(), layout.align()); } } impl GlobalScudoAllocator { /// Prints the global Scudo allocator's internal statistics. pub fn print_stats() { unsafe { scudo_print_stats() } } } #[cfg(feature = "allocator_api")] use core::alloc::AllocError; #[cfg(feature = "allocator_api")] use core::ptr::NonNull; #[cfg(feature = "allocator_api")] unsafe impl core::alloc::Allocator for GlobalScudoAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = fit_layout(layout); // TODO(cneo): Scudo buckets and therefore overallocates. Use SizeClassMap to // return the correct length for the slice? let ptr = unsafe { scudo_allocate(layout.size(), layout.align()) } as _; let n = NonNull::new(ptr).ok_or(AllocError)?; Ok(NonNull::slice_from_raw_parts(n, layout.size())) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr.as_ptr() as _, layout.size(), layout.align()); } } #[cfg(test)] pub mod test { use super::*; use std::prelude::v1::*; use core::alloc::Layout; use libc::{c_ulong, c_void, size_t}; use scudo_sys::{scudo_disable, scudo_enable, scudo_iterate}; extern "C" fn contains(_address: c_ulong, size: size_t, pair: *mut c_void) { let (target_size, count) = unsafe { &mut *(pair as *mut (usize, usize)) }; if size == *target_size
} /// Test-only function that returns the number of allocations of a given size. fn count_allocations_by_size(size: usize) -> usize { let mut size_and_count = (size, 0usize); unsafe { scudo_disable(); scudo_iterate( contains, &mut size_and_count as *mut (usize, usize) as *mut c_void, ); scudo_enable(); } size_and_count.1 } #[test] fn test_alloc_and_dealloc_use_scudo() { let a = GlobalScudoAllocator; let layout = Layout::from_size_align(4242, 16).unwrap(); assert_eq!(count_allocations_by_size(4242), 0); let p = unsafe { a.alloc(layout) }; assert_eq!(count_allocations_by_size(4242), 1); unsafe { a.dealloc(p, layout) }; assert_eq!(count_allocations_by_size(4242), 0); } #[global_allocator] static A: GlobalScudoAllocator = GlobalScudoAllocator; #[test] fn test_vec_uses_scudo() { assert_eq!(count_allocations_by_size(8200_1337), 0); let mut v = vec![8u8; 8200_1337]; assert_eq!(count_allocations_by_size(8200_1337), 1); v.clear(); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_1337), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_vec_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(8200_4242), 0); let mut v = Vec::<u8, GlobalScudoAllocator>::with_capacity_in(8200_4242, A); assert_eq!(count_allocations_by_size(8200_4242), 1); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_4242), 0); } #[test] fn test_box_uses_scudo() { assert_eq!(count_allocations_by_size(20), 0); let b = Box::new([3.0f32; 5]); assert_eq!(count_allocations_by_size(20), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(20), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_box_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(28), 0); let b = Box::new_in([3.0f32; 7], A); assert_eq!(count_allocations_by_size(28), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(28), 0); } #[test] fn test_1byte_box_uses_scudo() { // Unlike the other arbitrary size allocations, it seems // Rust's test harness does have some 1 byte allocations so we cannot // assert there are 0, then 1, then 0. let before = count_allocations_by_size(1); let b = Box::new(1i8); assert_eq!(count_allocations_by_size(1), before + 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(1), before); } }
{ *count += 1; }
conditional_block
lib.rs
// Copyright 2021 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 // // https://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. #![no_std] #![cfg_attr(feature = "allocator_api", feature(allocator_api))] #![cfg_attr(feature = "allocator_api", feature(nonnull_slice_from_raw_parts))] #[cfg(test)] #[macro_use] extern crate std; use scudo_sys::{scudo_allocate, scudo_deallocate, scudo_print_stats, SCUDO_MIN_ALIGN}; use core::alloc::{GlobalAlloc, Layout}; use core::cmp::max; /// Zero sized type representing the global static scudo allocator declared in C. #[derive(Clone, Copy)] pub struct GlobalScudoAllocator; /// Returns `layout` or the minimum size/align layout for scudo if its too small. fn fit_layout(layout: Layout) -> Layout { // SAFETY: SCUDO_MIN_ALIGN is constant and known to be powers of 2. let min_align = unsafe { SCUDO_MIN_ALIGN } as usize; let align = max(min_align, layout.align()); // SAFETY: Size and align are good by construction. unsafe { Layout::from_size_align_unchecked(layout.size(), align) } } unsafe impl GlobalAlloc for GlobalScudoAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let layout = fit_layout(layout); scudo_allocate(layout.size(), layout.align()) as _ } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr as _, layout.size(), layout.align()); } } impl GlobalScudoAllocator { /// Prints the global Scudo allocator's internal statistics. pub fn print_stats() { unsafe { scudo_print_stats() } } } #[cfg(feature = "allocator_api")] use core::alloc::AllocError; #[cfg(feature = "allocator_api")] use core::ptr::NonNull; #[cfg(feature = "allocator_api")] unsafe impl core::alloc::Allocator for GlobalScudoAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = fit_layout(layout); // TODO(cneo): Scudo buckets and therefore overallocates. Use SizeClassMap to // return the correct length for the slice? let ptr = unsafe { scudo_allocate(layout.size(), layout.align()) } as _; let n = NonNull::new(ptr).ok_or(AllocError)?; Ok(NonNull::slice_from_raw_parts(n, layout.size())) } unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let layout = fit_layout(layout); scudo_deallocate(ptr.as_ptr() as _, layout.size(), layout.align()); } } #[cfg(test)] pub mod test { use super::*; use std::prelude::v1::*; use core::alloc::Layout; use libc::{c_ulong, c_void, size_t}; use scudo_sys::{scudo_disable, scudo_enable, scudo_iterate}; extern "C" fn contains(_address: c_ulong, size: size_t, pair: *mut c_void) { let (target_size, count) = unsafe { &mut *(pair as *mut (usize, usize)) }; if size == *target_size { *count += 1; } } /// Test-only function that returns the number of allocations of a given size. fn count_allocations_by_size(size: usize) -> usize { let mut size_and_count = (size, 0usize); unsafe { scudo_disable(); scudo_iterate( contains, &mut size_and_count as *mut (usize, usize) as *mut c_void, ); scudo_enable(); } size_and_count.1 } #[test] fn test_alloc_and_dealloc_use_scudo() { let a = GlobalScudoAllocator; let layout = Layout::from_size_align(4242, 16).unwrap(); assert_eq!(count_allocations_by_size(4242), 0); let p = unsafe { a.alloc(layout) }; assert_eq!(count_allocations_by_size(4242), 1); unsafe { a.dealloc(p, layout) }; assert_eq!(count_allocations_by_size(4242), 0); } #[global_allocator] static A: GlobalScudoAllocator = GlobalScudoAllocator; #[test] fn test_vec_uses_scudo() { assert_eq!(count_allocations_by_size(8200_1337), 0); let mut v = vec![8u8; 8200_1337]; assert_eq!(count_allocations_by_size(8200_1337), 1); v.clear(); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_1337), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_vec_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(8200_4242), 0); let mut v = Vec::<u8, GlobalScudoAllocator>::with_capacity_in(8200_4242, A); assert_eq!(count_allocations_by_size(8200_4242), 1); v.shrink_to_fit(); assert_eq!(count_allocations_by_size(8200_4242), 0); } #[test] fn test_box_uses_scudo() { assert_eq!(count_allocations_by_size(20), 0); let b = Box::new([3.0f32; 5]); assert_eq!(count_allocations_by_size(20), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(20), 0); } #[cfg(feature = "allocator_api")] #[test] fn test_box_with_custom_allocator_uses_scudo() { assert_eq!(count_allocations_by_size(28), 0); let b = Box::new_in([3.0f32; 7], A); assert_eq!(count_allocations_by_size(28), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(28), 0); } #[test] fn
() { // Unlike the other arbitrary size allocations, it seems // Rust's test harness does have some 1 byte allocations so we cannot // assert there are 0, then 1, then 0. let before = count_allocations_by_size(1); let b = Box::new(1i8); assert_eq!(count_allocations_by_size(1), before + 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(1), before); } }
test_1byte_box_uses_scudo
identifier_name
15.2.3.6-4-372.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-372.js * @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is false, [[Configurable]] is true) to different value */ function testcase() { var obj = {}; Object.defineProperty(obj, "prop", { value: 2010,
enumerable: false, configurable: true }); var propertyDefineCorrect = obj.hasOwnProperty("prop"); var desc1 = Object.getOwnPropertyDescriptor(obj, "prop"); Object.defineProperty(obj, "prop", { enumerable: true }); var desc2 = Object.getOwnPropertyDescriptor(obj, "prop"); return propertyDefineCorrect && desc1.enumerable === false && obj.prop === 2010 && desc2.enumerable === true; } runTestCase(testcase);
writable: false,
random_line_split
15.2.3.6-4-372.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-372.js * @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is false, [[Configurable]] is true) to different value */ function testcase()
runTestCase(testcase);
{ var obj = {}; Object.defineProperty(obj, "prop", { value: 2010, writable: false, enumerable: false, configurable: true }); var propertyDefineCorrect = obj.hasOwnProperty("prop"); var desc1 = Object.getOwnPropertyDescriptor(obj, "prop"); Object.defineProperty(obj, "prop", { enumerable: true }); var desc2 = Object.getOwnPropertyDescriptor(obj, "prop"); return propertyDefineCorrect && desc1.enumerable === false && obj.prop === 2010 && desc2.enumerable === true; }
identifier_body
15.2.3.6-4-372.js
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-372.js * @description ES5 Attributes - success to update [[Enumerable]] attribute of data property ([[Writable]] is false, [[Enumerable]] is false, [[Configurable]] is true) to different value */ function
() { var obj = {}; Object.defineProperty(obj, "prop", { value: 2010, writable: false, enumerable: false, configurable: true }); var propertyDefineCorrect = obj.hasOwnProperty("prop"); var desc1 = Object.getOwnPropertyDescriptor(obj, "prop"); Object.defineProperty(obj, "prop", { enumerable: true }); var desc2 = Object.getOwnPropertyDescriptor(obj, "prop"); return propertyDefineCorrect && desc1.enumerable === false && obj.prop === 2010 && desc2.enumerable === true; } runTestCase(testcase);
testcase
identifier_name
transit.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #![allow(non_snake_case)] extern crate astro; use astro::*; #[test] #[allow(unused_variables)] fn
() { let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), dec: 18.44092_f64.to_radians() }; let eq_point3 = coords::EqPoint{ asc: 42.78204_f64.to_radians(), dec: 18.82742_f64.to_radians() }; let geograph_point = coords::GeographPoint{ long: 71.0833_f64.to_radians(), lat: 42.3333_f64.to_radians(), }; let Theta0 = 177.74208_f64.to_radians(); let deltaT = time::delta_t(1988, 3); let (h_rise, m_rise, s_rise) = transit::time( &transit::TransitType::Rise, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_rise, m_rise), (12, 25)); let (h_transit, m_transit, s_transit) = transit::time( &transit::TransitType::Transit, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_transit, m_transit), (19, 40)); let (h_set, m_set, s_set) = transit::time( &transit::TransitType::Set, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_set, m_set), (2, 54)); }
time
identifier_name
transit.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #![allow(non_snake_case)] extern crate astro; use astro::*; #[test] #[allow(unused_variables)] fn time()
{ let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), dec: 18.44092_f64.to_radians() }; let eq_point3 = coords::EqPoint{ asc: 42.78204_f64.to_radians(), dec: 18.82742_f64.to_radians() }; let geograph_point = coords::GeographPoint{ long: 71.0833_f64.to_radians(), lat: 42.3333_f64.to_radians(), }; let Theta0 = 177.74208_f64.to_radians(); let deltaT = time::delta_t(1988, 3); let (h_rise, m_rise, s_rise) = transit::time( &transit::TransitType::Rise, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_rise, m_rise), (12, 25)); let (h_transit, m_transit, s_transit) = transit::time( &transit::TransitType::Transit, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_transit, m_transit), (19, 40)); let (h_set, m_set, s_set) = transit::time( &transit::TransitType::Set, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_set, m_set), (2, 54)); }
identifier_body
transit.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#![allow(non_snake_case)] extern crate astro; use astro::*; #[test] #[allow(unused_variables)] fn time() { let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), dec: 18.44092_f64.to_radians() }; let eq_point3 = coords::EqPoint{ asc: 42.78204_f64.to_radians(), dec: 18.82742_f64.to_radians() }; let geograph_point = coords::GeographPoint{ long: 71.0833_f64.to_radians(), lat: 42.3333_f64.to_radians(), }; let Theta0 = 177.74208_f64.to_radians(); let deltaT = time::delta_t(1988, 3); let (h_rise, m_rise, s_rise) = transit::time( &transit::TransitType::Rise, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_rise, m_rise), (12, 25)); let (h_transit, m_transit, s_transit) = transit::time( &transit::TransitType::Transit, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_transit, m_transit), (19, 40)); let (h_set, m_set, s_set) = transit::time( &transit::TransitType::Set, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0, deltaT, 0.0 ); assert_eq!((h_set, m_set), (2, 54)); }
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
random_line_split
nbbase.py
"""Python API for composing notebook elements The Python representation of a notebook is a nested structure of dictionary subclasses that support attribute access (IPython.utils.ipstruct.Struct). The functions in this module are merely helpers to build the structs in the right form. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from ..notebooknode import from_dict, NotebookNode # Change this when incrementing the nbformat version nbformat = 4 nbformat_minor = 1 nbformat_schema = 'nbformat.v4.schema.json' def validate(node, ref=None): """validate a v4 node""" from .. import validate return validate(node, ref=ref, version=nbformat) def new_output(output_type, data=None, **kwargs): """Create a new output, to go in the ``cell.outputs`` list of a code cell.""" output = NotebookNode(output_type=output_type) # populate defaults: if output_type == 'stream': output.name = u'stdout' output.text = u'' elif output_type in {'execute_result', 'display_data'}: output.metadata = NotebookNode() output.data = NotebookNode() # load from args: output.update(from_dict(kwargs)) if data is not None: output.data = from_dict(data) # validate validate(output, output_type) return output def output_from_msg(msg): """Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. """ msg_type = msg['header']['msg_type'] content = msg['content'] if msg_type == 'execute_result': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], execution_count=content['execution_count'], ) elif msg_type == 'stream': return new_output(output_type=msg_type, name=content['name'], text=content['text'], ) elif msg_type == 'display_data': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], ) elif msg_type == 'error': return new_output(output_type=msg_type, ename=content['ename'], evalue=content['evalue'], traceback=content['traceback'], ) else: raise ValueError("Unrecognized output msg type: %r" % msg_type) def new_code_cell(source='', **kwargs): """Create a new code cell""" cell = NotebookNode( cell_type='code', metadata=NotebookNode(), execution_count=None, source=source, outputs=[], ) cell.update(from_dict(kwargs)) validate(cell, 'code_cell') return cell def
(source='', **kwargs): """Create a new markdown cell""" cell = NotebookNode( cell_type='markdown', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'markdown_cell') return cell def new_raw_cell(source='', **kwargs): """Create a new raw cell""" cell = NotebookNode( cell_type='raw', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'raw_cell') return cell def new_worksheet(name=None, cells=None, metadata=None): """Create a worksheet by name with with a list of cells.""" ws = NotebookNode() if cells is None: ws.cells = [] else: ws.cells = list(cells) ws.metadata = NotebookNode(metadata or {}) return ws def new_notebook(name=None, metadata=None, worksheets=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor if worksheets is None: nb.worksheets = [] else: nb.worksheets = list(worksheets) if metadata is None: nb.metadata = new_metadata() else: nb.metadata = NotebookNode(metadata) if name is not None: nb.metadata.name = cast_unicode(name) return nb def new_metadata(name=None, authors=None, license=None, created=None, modified=None, gistid=None): """Create a new metadata node.""" metadata = NotebookNode() if name is not None: metadata.name = cast_unicode(name) if authors is not None: metadata.authors = list(authors) if created is not None: metadata.created = cast_unicode(created) if modified is not None: metadata.modified = cast_unicode(modified) if license is not None: metadata.license = cast_unicode(license) if gistid is not None: metadata.gistid = cast_unicode(gistid) return metadata
new_markdown_cell
identifier_name
nbbase.py
"""Python API for composing notebook elements The Python representation of a notebook is a nested structure of dictionary subclasses that support attribute access (IPython.utils.ipstruct.Struct). The functions in this module are merely helpers to build the structs in the right form. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from ..notebooknode import from_dict, NotebookNode # Change this when incrementing the nbformat version nbformat = 4 nbformat_minor = 1 nbformat_schema = 'nbformat.v4.schema.json' def validate(node, ref=None): """validate a v4 node""" from .. import validate return validate(node, ref=ref, version=nbformat) def new_output(output_type, data=None, **kwargs): """Create a new output, to go in the ``cell.outputs`` list of a code cell.""" output = NotebookNode(output_type=output_type) # populate defaults: if output_type == 'stream': output.name = u'stdout' output.text = u'' elif output_type in {'execute_result', 'display_data'}: output.metadata = NotebookNode() output.data = NotebookNode() # load from args: output.update(from_dict(kwargs)) if data is not None: output.data = from_dict(data) # validate validate(output, output_type) return output def output_from_msg(msg): """Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. """ msg_type = msg['header']['msg_type']
if msg_type == 'execute_result': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], execution_count=content['execution_count'], ) elif msg_type == 'stream': return new_output(output_type=msg_type, name=content['name'], text=content['text'], ) elif msg_type == 'display_data': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], ) elif msg_type == 'error': return new_output(output_type=msg_type, ename=content['ename'], evalue=content['evalue'], traceback=content['traceback'], ) else: raise ValueError("Unrecognized output msg type: %r" % msg_type) def new_code_cell(source='', **kwargs): """Create a new code cell""" cell = NotebookNode( cell_type='code', metadata=NotebookNode(), execution_count=None, source=source, outputs=[], ) cell.update(from_dict(kwargs)) validate(cell, 'code_cell') return cell def new_markdown_cell(source='', **kwargs): """Create a new markdown cell""" cell = NotebookNode( cell_type='markdown', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'markdown_cell') return cell def new_raw_cell(source='', **kwargs): """Create a new raw cell""" cell = NotebookNode( cell_type='raw', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'raw_cell') return cell def new_worksheet(name=None, cells=None, metadata=None): """Create a worksheet by name with with a list of cells.""" ws = NotebookNode() if cells is None: ws.cells = [] else: ws.cells = list(cells) ws.metadata = NotebookNode(metadata or {}) return ws def new_notebook(name=None, metadata=None, worksheets=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor if worksheets is None: nb.worksheets = [] else: nb.worksheets = list(worksheets) if metadata is None: nb.metadata = new_metadata() else: nb.metadata = NotebookNode(metadata) if name is not None: nb.metadata.name = cast_unicode(name) return nb def new_metadata(name=None, authors=None, license=None, created=None, modified=None, gistid=None): """Create a new metadata node.""" metadata = NotebookNode() if name is not None: metadata.name = cast_unicode(name) if authors is not None: metadata.authors = list(authors) if created is not None: metadata.created = cast_unicode(created) if modified is not None: metadata.modified = cast_unicode(modified) if license is not None: metadata.license = cast_unicode(license) if gistid is not None: metadata.gistid = cast_unicode(gistid) return metadata
content = msg['content']
random_line_split
nbbase.py
"""Python API for composing notebook elements The Python representation of a notebook is a nested structure of dictionary subclasses that support attribute access (IPython.utils.ipstruct.Struct). The functions in this module are merely helpers to build the structs in the right form. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from ..notebooknode import from_dict, NotebookNode # Change this when incrementing the nbformat version nbformat = 4 nbformat_minor = 1 nbformat_schema = 'nbformat.v4.schema.json' def validate(node, ref=None): """validate a v4 node""" from .. import validate return validate(node, ref=ref, version=nbformat) def new_output(output_type, data=None, **kwargs): """Create a new output, to go in the ``cell.outputs`` list of a code cell.""" output = NotebookNode(output_type=output_type) # populate defaults: if output_type == 'stream': output.name = u'stdout' output.text = u'' elif output_type in {'execute_result', 'display_data'}: output.metadata = NotebookNode() output.data = NotebookNode() # load from args: output.update(from_dict(kwargs)) if data is not None: output.data = from_dict(data) # validate validate(output, output_type) return output def output_from_msg(msg): """Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. """ msg_type = msg['header']['msg_type'] content = msg['content'] if msg_type == 'execute_result': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], execution_count=content['execution_count'], ) elif msg_type == 'stream': return new_output(output_type=msg_type, name=content['name'], text=content['text'], ) elif msg_type == 'display_data': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], ) elif msg_type == 'error': return new_output(output_type=msg_type, ename=content['ename'], evalue=content['evalue'], traceback=content['traceback'], ) else: raise ValueError("Unrecognized output msg type: %r" % msg_type) def new_code_cell(source='', **kwargs): """Create a new code cell""" cell = NotebookNode( cell_type='code', metadata=NotebookNode(), execution_count=None, source=source, outputs=[], ) cell.update(from_dict(kwargs)) validate(cell, 'code_cell') return cell def new_markdown_cell(source='', **kwargs): """Create a new markdown cell""" cell = NotebookNode( cell_type='markdown', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'markdown_cell') return cell def new_raw_cell(source='', **kwargs): """Create a new raw cell""" cell = NotebookNode( cell_type='raw', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'raw_cell') return cell def new_worksheet(name=None, cells=None, metadata=None):
def new_notebook(name=None, metadata=None, worksheets=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor if worksheets is None: nb.worksheets = [] else: nb.worksheets = list(worksheets) if metadata is None: nb.metadata = new_metadata() else: nb.metadata = NotebookNode(metadata) if name is not None: nb.metadata.name = cast_unicode(name) return nb def new_metadata(name=None, authors=None, license=None, created=None, modified=None, gistid=None): """Create a new metadata node.""" metadata = NotebookNode() if name is not None: metadata.name = cast_unicode(name) if authors is not None: metadata.authors = list(authors) if created is not None: metadata.created = cast_unicode(created) if modified is not None: metadata.modified = cast_unicode(modified) if license is not None: metadata.license = cast_unicode(license) if gistid is not None: metadata.gistid = cast_unicode(gistid) return metadata
"""Create a worksheet by name with with a list of cells.""" ws = NotebookNode() if cells is None: ws.cells = [] else: ws.cells = list(cells) ws.metadata = NotebookNode(metadata or {}) return ws
identifier_body
nbbase.py
"""Python API for composing notebook elements The Python representation of a notebook is a nested structure of dictionary subclasses that support attribute access (IPython.utils.ipstruct.Struct). The functions in this module are merely helpers to build the structs in the right form. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from ..notebooknode import from_dict, NotebookNode # Change this when incrementing the nbformat version nbformat = 4 nbformat_minor = 1 nbformat_schema = 'nbformat.v4.schema.json' def validate(node, ref=None): """validate a v4 node""" from .. import validate return validate(node, ref=ref, version=nbformat) def new_output(output_type, data=None, **kwargs): """Create a new output, to go in the ``cell.outputs`` list of a code cell.""" output = NotebookNode(output_type=output_type) # populate defaults: if output_type == 'stream': output.name = u'stdout' output.text = u'' elif output_type in {'execute_result', 'display_data'}: output.metadata = NotebookNode() output.data = NotebookNode() # load from args: output.update(from_dict(kwargs)) if data is not None: output.data = from_dict(data) # validate validate(output, output_type) return output def output_from_msg(msg): """Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. """ msg_type = msg['header']['msg_type'] content = msg['content'] if msg_type == 'execute_result': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], execution_count=content['execution_count'], ) elif msg_type == 'stream': return new_output(output_type=msg_type, name=content['name'], text=content['text'], ) elif msg_type == 'display_data': return new_output(output_type=msg_type, metadata=content['metadata'], data=content['data'], ) elif msg_type == 'error': return new_output(output_type=msg_type, ename=content['ename'], evalue=content['evalue'], traceback=content['traceback'], ) else: raise ValueError("Unrecognized output msg type: %r" % msg_type) def new_code_cell(source='', **kwargs): """Create a new code cell""" cell = NotebookNode( cell_type='code', metadata=NotebookNode(), execution_count=None, source=source, outputs=[], ) cell.update(from_dict(kwargs)) validate(cell, 'code_cell') return cell def new_markdown_cell(source='', **kwargs): """Create a new markdown cell""" cell = NotebookNode( cell_type='markdown', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'markdown_cell') return cell def new_raw_cell(source='', **kwargs): """Create a new raw cell""" cell = NotebookNode( cell_type='raw', source=source, metadata=NotebookNode(), ) cell.update(from_dict(kwargs)) validate(cell, 'raw_cell') return cell def new_worksheet(name=None, cells=None, metadata=None): """Create a worksheet by name with with a list of cells.""" ws = NotebookNode() if cells is None: ws.cells = [] else: ws.cells = list(cells) ws.metadata = NotebookNode(metadata or {}) return ws def new_notebook(name=None, metadata=None, worksheets=None): """Create a notebook by name, id and a list of worksheets.""" nb = NotebookNode() nb.nbformat = nbformat nb.nbformat_minor = nbformat_minor if worksheets is None: nb.worksheets = [] else:
if metadata is None: nb.metadata = new_metadata() else: nb.metadata = NotebookNode(metadata) if name is not None: nb.metadata.name = cast_unicode(name) return nb def new_metadata(name=None, authors=None, license=None, created=None, modified=None, gistid=None): """Create a new metadata node.""" metadata = NotebookNode() if name is not None: metadata.name = cast_unicode(name) if authors is not None: metadata.authors = list(authors) if created is not None: metadata.created = cast_unicode(created) if modified is not None: metadata.modified = cast_unicode(modified) if license is not None: metadata.license = cast_unicode(license) if gistid is not None: metadata.gistid = cast_unicode(gistid) return metadata
nb.worksheets = list(worksheets)
conditional_block
util.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import with_statement import glob import os import hmac import hashlib import shutil import socket import subprocess import struct from twisted.internet import defer from twisted.internet.interfaces import IProtocolFactory from twisted.internet.endpoints import serverFromString from zope.interface import implementer try: import GeoIP as _GeoIP GeoIP = _GeoIP except ImportError: GeoIP = None city = None country = None asn = None # XXX probably better to depend on and use "six" for py2/3 stuff? try: unicode except NameError: py3k = True basestring = str else: py3k = False basestring = basestring def create_geoip(fname): # It's more "pythonic" to just wait for the exception, # but GeoIP prints out "Can't open..." messages for you, # which isn't desired here if not os.path.isfile(fname): raise IOError("Can't find %s" % fname) if GeoIP is None: return None # just letting any errors make it out return GeoIP.open(fname, GeoIP.GEOIP_STANDARD) def maybe_create_db(path): try: return create_geoip(path) except IOError: return None city, asn, country = list(map(maybe_create_db, ("/usr/share/GeoIP/GeoLiteCity.dat", "/usr/share/GeoIP/GeoIPASNum.dat", "/usr/share/GeoIP/GeoIP.dat"))) try: import ipaddr as _ipaddr ipaddr = _ipaddr except ImportError: ipaddr = None def is_executable(path): """Checks if the given path points to an existing, executable file""" return os.path.isfile(path) and os.access(path, os.X_OK) def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/', '/Applications/TorBrowser_*.app/Contents/MacOS/'), system_tor=True): """ Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple. """ # Try to find the tor executable using the shell if system_tor: try: proc = subprocess.Popen( ('which tor'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) except OSError: pass else: stdout, _ = proc.communicate() if proc.poll() == 0 and stdout != '': return stdout.strip() # the shell may not provide type and tor is usually not on PATH when using # the browser-bundle. Look in specific places for pattern in globs: for path in glob.glob(pattern): torbin = os.path.join(path, 'tor') if is_executable(torbin): return torbin return None def maybe_ip_addr(addr): """ Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end? """ if ipaddr is not None: try: return ipaddr.IPAddress(addr) except ValueError: pass return str(addr) def find_keywords(args, key_filter=lambda x: not x.startswith("$")): """ This splits up strings like name=value, foo=bar into a dict. Does NOT deal with quotes in value (e.g. key="value with space" will not work By default, note that it takes OUT any key which starts with $ (i.e. a single dollar sign) since for many use-cases the way Tor encodes nodes with "$hash=name" looks like a keyword argument (but it isn't). If you don't want this, override the "key_filter" argument to this method. :return: a dict of key->value (both strings) of all name=value type keywords found in args. """ filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])] return dict(x.split('=', 1) for x in filtered) def
(*args): """ For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors. """ for f in args: try: os.unlink(f) except OSError: shutil.rmtree(f, ignore_errors=True) def ip_from_int(ip): """ Convert long int back to dotted quad string """ return socket.inet_ntoa(struct.pack('>I', ip)) def process_from_address(addr, port, torstate=None): """ Determines the PID from the address/port provided by using lsof and returns it as an int (or None if it couldn't be determined). In the special case the addr is '(Tor_internal)' then the PID of the Tor process (as gotten from the torstate object) is returned (or 0 if unavailable, e.g. a Tor which doesn't implement 'GETINFO process/pid'). In this case if no TorState instance is given, None is returned. """ if addr is None: return None if "(tor_internal)" == str(addr).lower(): if torstate is None: return None return int(torstate.tor_pid) proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)], stdout=subprocess.PIPE) (stdout, stderr) = proc.communicate() lines = stdout.split('\n') if len(lines) > 1: return int(lines[1].split()[1]) def hmac_sha256(key, msg): """ Adapted from rransom's tor-utils git repository. Returns the digest (binary) of an HMAC with SHA256 over msg with key. """ return hmac.new(key, msg, hashlib.sha256).digest() CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE = os.urandom(32) def compare_via_hash(x, y): """ Taken from rransom's tor-utils git repository, to compare two hashes in something resembling constant time (or at least, not leaking timing info?) """ return (hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) == hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y)) class NetLocation: """ Represents the location of an IP address, either city or country level resolution depending on what GeoIP database was loaded. If the ASN database is available you get that also. """ def __init__(self, ipaddr): "ipaddr should be a dotted-quad" self.ip = ipaddr self.latlng = (None, None) self.countrycode = None self.city = None self.asn = None if self.ip is None or self.ip == 'unknown': return if city: try: r = city.record_by_addr(self.ip) except: r = None if r is not None: self.countrycode = r['country_code'] self.latlng = (r['latitude'], r['longitude']) try: self.city = (r['city'], r['region_code']) except KeyError: self.city = (r['city'], r['region_name']) elif country: self.countrycode = country.country_code_by_addr(ipaddr) else: self.countrycode = '' if asn: try: self.asn = asn.org_by_addr(self.ip) except: self.asn = None @implementer(IProtocolFactory) class NoOpProtocolFactory: """ This is an IProtocolFactory that does nothing. Used for testing, and for :method:`available_tcp_port` """ def noop(self, *args, **kw): pass buildProtocol = noop doStart = noop doStop = noop @defer.inlineCallbacks def available_tcp_port(reactor): """ Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number. """ endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1') port = yield endpoint.listen(NoOpProtocolFactory()) address = port.getHost() yield port.stopListening() defer.returnValue(address.port)
delete_file_or_tree
identifier_name
util.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import with_statement import glob import os import hmac import hashlib import shutil import socket import subprocess import struct from twisted.internet import defer from twisted.internet.interfaces import IProtocolFactory from twisted.internet.endpoints import serverFromString from zope.interface import implementer try: import GeoIP as _GeoIP GeoIP = _GeoIP except ImportError: GeoIP = None city = None country = None asn = None # XXX probably better to depend on and use "six" for py2/3 stuff? try: unicode except NameError: py3k = True basestring = str else: py3k = False basestring = basestring def create_geoip(fname): # It's more "pythonic" to just wait for the exception, # but GeoIP prints out "Can't open..." messages for you, # which isn't desired here if not os.path.isfile(fname): raise IOError("Can't find %s" % fname) if GeoIP is None: return None # just letting any errors make it out return GeoIP.open(fname, GeoIP.GEOIP_STANDARD) def maybe_create_db(path): try: return create_geoip(path) except IOError: return None city, asn, country = list(map(maybe_create_db, ("/usr/share/GeoIP/GeoLiteCity.dat", "/usr/share/GeoIP/GeoIPASNum.dat", "/usr/share/GeoIP/GeoIP.dat"))) try: import ipaddr as _ipaddr ipaddr = _ipaddr except ImportError: ipaddr = None def is_executable(path): """Checks if the given path points to an existing, executable file""" return os.path.isfile(path) and os.access(path, os.X_OK) def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/', '/Applications/TorBrowser_*.app/Contents/MacOS/'), system_tor=True): """ Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple. """ # Try to find the tor executable using the shell if system_tor: try: proc = subprocess.Popen( ('which tor'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) except OSError: pass else: stdout, _ = proc.communicate() if proc.poll() == 0 and stdout != '': return stdout.strip() # the shell may not provide type and tor is usually not on PATH when using # the browser-bundle. Look in specific places for pattern in globs: for path in glob.glob(pattern): torbin = os.path.join(path, 'tor') if is_executable(torbin): return torbin return None def maybe_ip_addr(addr):
def find_keywords(args, key_filter=lambda x: not x.startswith("$")): """ This splits up strings like name=value, foo=bar into a dict. Does NOT deal with quotes in value (e.g. key="value with space" will not work By default, note that it takes OUT any key which starts with $ (i.e. a single dollar sign) since for many use-cases the way Tor encodes nodes with "$hash=name" looks like a keyword argument (but it isn't). If you don't want this, override the "key_filter" argument to this method. :return: a dict of key->value (both strings) of all name=value type keywords found in args. """ filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])] return dict(x.split('=', 1) for x in filtered) def delete_file_or_tree(*args): """ For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors. """ for f in args: try: os.unlink(f) except OSError: shutil.rmtree(f, ignore_errors=True) def ip_from_int(ip): """ Convert long int back to dotted quad string """ return socket.inet_ntoa(struct.pack('>I', ip)) def process_from_address(addr, port, torstate=None): """ Determines the PID from the address/port provided by using lsof and returns it as an int (or None if it couldn't be determined). In the special case the addr is '(Tor_internal)' then the PID of the Tor process (as gotten from the torstate object) is returned (or 0 if unavailable, e.g. a Tor which doesn't implement 'GETINFO process/pid'). In this case if no TorState instance is given, None is returned. """ if addr is None: return None if "(tor_internal)" == str(addr).lower(): if torstate is None: return None return int(torstate.tor_pid) proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)], stdout=subprocess.PIPE) (stdout, stderr) = proc.communicate() lines = stdout.split('\n') if len(lines) > 1: return int(lines[1].split()[1]) def hmac_sha256(key, msg): """ Adapted from rransom's tor-utils git repository. Returns the digest (binary) of an HMAC with SHA256 over msg with key. """ return hmac.new(key, msg, hashlib.sha256).digest() CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE = os.urandom(32) def compare_via_hash(x, y): """ Taken from rransom's tor-utils git repository, to compare two hashes in something resembling constant time (or at least, not leaking timing info?) """ return (hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) == hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y)) class NetLocation: """ Represents the location of an IP address, either city or country level resolution depending on what GeoIP database was loaded. If the ASN database is available you get that also. """ def __init__(self, ipaddr): "ipaddr should be a dotted-quad" self.ip = ipaddr self.latlng = (None, None) self.countrycode = None self.city = None self.asn = None if self.ip is None or self.ip == 'unknown': return if city: try: r = city.record_by_addr(self.ip) except: r = None if r is not None: self.countrycode = r['country_code'] self.latlng = (r['latitude'], r['longitude']) try: self.city = (r['city'], r['region_code']) except KeyError: self.city = (r['city'], r['region_name']) elif country: self.countrycode = country.country_code_by_addr(ipaddr) else: self.countrycode = '' if asn: try: self.asn = asn.org_by_addr(self.ip) except: self.asn = None @implementer(IProtocolFactory) class NoOpProtocolFactory: """ This is an IProtocolFactory that does nothing. Used for testing, and for :method:`available_tcp_port` """ def noop(self, *args, **kw): pass buildProtocol = noop doStart = noop doStop = noop @defer.inlineCallbacks def available_tcp_port(reactor): """ Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number. """ endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1') port = yield endpoint.listen(NoOpProtocolFactory()) address = port.getHost() yield port.stopListening() defer.returnValue(address.port)
""" Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end? """ if ipaddr is not None: try: return ipaddr.IPAddress(addr) except ValueError: pass return str(addr)
identifier_body
util.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import with_statement import glob import os import hmac import hashlib import shutil import socket import subprocess import struct from twisted.internet import defer from twisted.internet.interfaces import IProtocolFactory from twisted.internet.endpoints import serverFromString from zope.interface import implementer try: import GeoIP as _GeoIP GeoIP = _GeoIP except ImportError: GeoIP = None city = None country = None asn = None # XXX probably better to depend on and use "six" for py2/3 stuff? try: unicode except NameError: py3k = True basestring = str else: py3k = False basestring = basestring def create_geoip(fname): # It's more "pythonic" to just wait for the exception, # but GeoIP prints out "Can't open..." messages for you, # which isn't desired here if not os.path.isfile(fname): raise IOError("Can't find %s" % fname) if GeoIP is None: return None # just letting any errors make it out return GeoIP.open(fname, GeoIP.GEOIP_STANDARD) def maybe_create_db(path): try:
except IOError: return None city, asn, country = list(map(maybe_create_db, ("/usr/share/GeoIP/GeoLiteCity.dat", "/usr/share/GeoIP/GeoIPASNum.dat", "/usr/share/GeoIP/GeoIP.dat"))) try: import ipaddr as _ipaddr ipaddr = _ipaddr except ImportError: ipaddr = None def is_executable(path): """Checks if the given path points to an existing, executable file""" return os.path.isfile(path) and os.access(path, os.X_OK) def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/', '/Applications/TorBrowser_*.app/Contents/MacOS/'), system_tor=True): """ Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple. """ # Try to find the tor executable using the shell if system_tor: try: proc = subprocess.Popen( ('which tor'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) except OSError: pass else: stdout, _ = proc.communicate() if proc.poll() == 0 and stdout != '': return stdout.strip() # the shell may not provide type and tor is usually not on PATH when using # the browser-bundle. Look in specific places for pattern in globs: for path in glob.glob(pattern): torbin = os.path.join(path, 'tor') if is_executable(torbin): return torbin return None def maybe_ip_addr(addr): """ Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end? """ if ipaddr is not None: try: return ipaddr.IPAddress(addr) except ValueError: pass return str(addr) def find_keywords(args, key_filter=lambda x: not x.startswith("$")): """ This splits up strings like name=value, foo=bar into a dict. Does NOT deal with quotes in value (e.g. key="value with space" will not work By default, note that it takes OUT any key which starts with $ (i.e. a single dollar sign) since for many use-cases the way Tor encodes nodes with "$hash=name" looks like a keyword argument (but it isn't). If you don't want this, override the "key_filter" argument to this method. :return: a dict of key->value (both strings) of all name=value type keywords found in args. """ filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])] return dict(x.split('=', 1) for x in filtered) def delete_file_or_tree(*args): """ For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors. """ for f in args: try: os.unlink(f) except OSError: shutil.rmtree(f, ignore_errors=True) def ip_from_int(ip): """ Convert long int back to dotted quad string """ return socket.inet_ntoa(struct.pack('>I', ip)) def process_from_address(addr, port, torstate=None): """ Determines the PID from the address/port provided by using lsof and returns it as an int (or None if it couldn't be determined). In the special case the addr is '(Tor_internal)' then the PID of the Tor process (as gotten from the torstate object) is returned (or 0 if unavailable, e.g. a Tor which doesn't implement 'GETINFO process/pid'). In this case if no TorState instance is given, None is returned. """ if addr is None: return None if "(tor_internal)" == str(addr).lower(): if torstate is None: return None return int(torstate.tor_pid) proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)], stdout=subprocess.PIPE) (stdout, stderr) = proc.communicate() lines = stdout.split('\n') if len(lines) > 1: return int(lines[1].split()[1]) def hmac_sha256(key, msg): """ Adapted from rransom's tor-utils git repository. Returns the digest (binary) of an HMAC with SHA256 over msg with key. """ return hmac.new(key, msg, hashlib.sha256).digest() CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE = os.urandom(32) def compare_via_hash(x, y): """ Taken from rransom's tor-utils git repository, to compare two hashes in something resembling constant time (or at least, not leaking timing info?) """ return (hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) == hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y)) class NetLocation: """ Represents the location of an IP address, either city or country level resolution depending on what GeoIP database was loaded. If the ASN database is available you get that also. """ def __init__(self, ipaddr): "ipaddr should be a dotted-quad" self.ip = ipaddr self.latlng = (None, None) self.countrycode = None self.city = None self.asn = None if self.ip is None or self.ip == 'unknown': return if city: try: r = city.record_by_addr(self.ip) except: r = None if r is not None: self.countrycode = r['country_code'] self.latlng = (r['latitude'], r['longitude']) try: self.city = (r['city'], r['region_code']) except KeyError: self.city = (r['city'], r['region_name']) elif country: self.countrycode = country.country_code_by_addr(ipaddr) else: self.countrycode = '' if asn: try: self.asn = asn.org_by_addr(self.ip) except: self.asn = None @implementer(IProtocolFactory) class NoOpProtocolFactory: """ This is an IProtocolFactory that does nothing. Used for testing, and for :method:`available_tcp_port` """ def noop(self, *args, **kw): pass buildProtocol = noop doStart = noop doStop = noop @defer.inlineCallbacks def available_tcp_port(reactor): """ Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number. """ endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1') port = yield endpoint.listen(NoOpProtocolFactory()) address = port.getHost() yield port.stopListening() defer.returnValue(address.port)
return create_geoip(path)
random_line_split
util.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import with_statement import glob import os import hmac import hashlib import shutil import socket import subprocess import struct from twisted.internet import defer from twisted.internet.interfaces import IProtocolFactory from twisted.internet.endpoints import serverFromString from zope.interface import implementer try: import GeoIP as _GeoIP GeoIP = _GeoIP except ImportError: GeoIP = None city = None country = None asn = None # XXX probably better to depend on and use "six" for py2/3 stuff? try: unicode except NameError: py3k = True basestring = str else: py3k = False basestring = basestring def create_geoip(fname): # It's more "pythonic" to just wait for the exception, # but GeoIP prints out "Can't open..." messages for you, # which isn't desired here if not os.path.isfile(fname): raise IOError("Can't find %s" % fname) if GeoIP is None: return None # just letting any errors make it out return GeoIP.open(fname, GeoIP.GEOIP_STANDARD) def maybe_create_db(path): try: return create_geoip(path) except IOError: return None city, asn, country = list(map(maybe_create_db, ("/usr/share/GeoIP/GeoLiteCity.dat", "/usr/share/GeoIP/GeoIPASNum.dat", "/usr/share/GeoIP/GeoIP.dat"))) try: import ipaddr as _ipaddr ipaddr = _ipaddr except ImportError: ipaddr = None def is_executable(path): """Checks if the given path points to an existing, executable file""" return os.path.isfile(path) and os.access(path, os.X_OK) def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/', '/Applications/TorBrowser_*.app/Contents/MacOS/'), system_tor=True): """ Tries to find the tor executable using the shell first or in in the paths whose glob-patterns is in the given 'globs'-tuple. :param globs: A tuple of shell-style globs of directories to use to find tor (TODO consider making that globs to actual tor binary?) :param system_tor: This controls whether bash is used to seach for 'tor' or not. If False, we skip that check and use only the 'globs' tuple. """ # Try to find the tor executable using the shell if system_tor: try: proc = subprocess.Popen( ('which tor'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) except OSError: pass else: stdout, _ = proc.communicate() if proc.poll() == 0 and stdout != '': return stdout.strip() # the shell may not provide type and tor is usually not on PATH when using # the browser-bundle. Look in specific places for pattern in globs: for path in glob.glob(pattern): torbin = os.path.join(path, 'tor') if is_executable(torbin): return torbin return None def maybe_ip_addr(addr): """ Tries to return an IPAddress, otherwise returns a string. TODO consider explicitly checking for .exit or .onion at the end? """ if ipaddr is not None: try: return ipaddr.IPAddress(addr) except ValueError: pass return str(addr) def find_keywords(args, key_filter=lambda x: not x.startswith("$")): """ This splits up strings like name=value, foo=bar into a dict. Does NOT deal with quotes in value (e.g. key="value with space" will not work By default, note that it takes OUT any key which starts with $ (i.e. a single dollar sign) since for many use-cases the way Tor encodes nodes with "$hash=name" looks like a keyword argument (but it isn't). If you don't want this, override the "key_filter" argument to this method. :return: a dict of key->value (both strings) of all name=value type keywords found in args. """ filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])] return dict(x.split('=', 1) for x in filtered) def delete_file_or_tree(*args): """ For every path in args, try to delete it as a file or a directory tree. Ignores deletion errors. """ for f in args: try: os.unlink(f) except OSError: shutil.rmtree(f, ignore_errors=True) def ip_from_int(ip): """ Convert long int back to dotted quad string """ return socket.inet_ntoa(struct.pack('>I', ip)) def process_from_address(addr, port, torstate=None): """ Determines the PID from the address/port provided by using lsof and returns it as an int (or None if it couldn't be determined). In the special case the addr is '(Tor_internal)' then the PID of the Tor process (as gotten from the torstate object) is returned (or 0 if unavailable, e.g. a Tor which doesn't implement 'GETINFO process/pid'). In this case if no TorState instance is given, None is returned. """ if addr is None: return None if "(tor_internal)" == str(addr).lower():
proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)], stdout=subprocess.PIPE) (stdout, stderr) = proc.communicate() lines = stdout.split('\n') if len(lines) > 1: return int(lines[1].split()[1]) def hmac_sha256(key, msg): """ Adapted from rransom's tor-utils git repository. Returns the digest (binary) of an HMAC with SHA256 over msg with key. """ return hmac.new(key, msg, hashlib.sha256).digest() CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE = os.urandom(32) def compare_via_hash(x, y): """ Taken from rransom's tor-utils git repository, to compare two hashes in something resembling constant time (or at least, not leaking timing info?) """ return (hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) == hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y)) class NetLocation: """ Represents the location of an IP address, either city or country level resolution depending on what GeoIP database was loaded. If the ASN database is available you get that also. """ def __init__(self, ipaddr): "ipaddr should be a dotted-quad" self.ip = ipaddr self.latlng = (None, None) self.countrycode = None self.city = None self.asn = None if self.ip is None or self.ip == 'unknown': return if city: try: r = city.record_by_addr(self.ip) except: r = None if r is not None: self.countrycode = r['country_code'] self.latlng = (r['latitude'], r['longitude']) try: self.city = (r['city'], r['region_code']) except KeyError: self.city = (r['city'], r['region_name']) elif country: self.countrycode = country.country_code_by_addr(ipaddr) else: self.countrycode = '' if asn: try: self.asn = asn.org_by_addr(self.ip) except: self.asn = None @implementer(IProtocolFactory) class NoOpProtocolFactory: """ This is an IProtocolFactory that does nothing. Used for testing, and for :method:`available_tcp_port` """ def noop(self, *args, **kw): pass buildProtocol = noop doStart = noop doStop = noop @defer.inlineCallbacks def available_tcp_port(reactor): """ Returns a Deferred firing an available TCP port on localhost. It does so by listening on port 0; then stopListening and fires the assigned port number. """ endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1') port = yield endpoint.listen(NoOpProtocolFactory()) address = port.getHost() yield port.stopListening() defer.returnValue(address.port)
if torstate is None: return None return int(torstate.tor_pid)
conditional_block
clipboard-paste-textarea.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Subject } from 'rxjs/Subject'; function onlyUnique(value, index, self): boolean { return self.indexOf(value) === index; } @Component({ selector: 'app-clipboard-paste-textarea', templateUrl: './clipboard-paste-textarea.component.html', styleUrls: ['./clipboard-paste-textarea.component.scss'] }) export class ClipboardPasteTextareaComponent implements OnInit { @Input() initialContent: string = ''; @Input() placeholder: string = 'paste stuff here'; @Input() distinctLines: boolean = false; @Output() changed = new EventEmitter(); search = new Subject<string>(); input: string = ''; constructor() { }
() { this.search .debounceTime(300) // wait for 300ms pause in events .distinctUntilChanged() // ignore if next search term is same as previous .map(text => text.split('\n').filter(str => str)) .map(lines => this.distinctLines ? lines.filter(onlyUnique) : lines) .subscribe(content => { this.changed.emit(content); }); if (this.initialContent) { this.input = this.initialContent; this.search.next(this.input); } } }
ngOnInit
identifier_name
clipboard-paste-textarea.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Subject } from 'rxjs/Subject'; function onlyUnique(value, index, self): boolean { return self.indexOf(value) === index; } @Component({ selector: 'app-clipboard-paste-textarea', templateUrl: './clipboard-paste-textarea.component.html',
export class ClipboardPasteTextareaComponent implements OnInit { @Input() initialContent: string = ''; @Input() placeholder: string = 'paste stuff here'; @Input() distinctLines: boolean = false; @Output() changed = new EventEmitter(); search = new Subject<string>(); input: string = ''; constructor() { } ngOnInit() { this.search .debounceTime(300) // wait for 300ms pause in events .distinctUntilChanged() // ignore if next search term is same as previous .map(text => text.split('\n').filter(str => str)) .map(lines => this.distinctLines ? lines.filter(onlyUnique) : lines) .subscribe(content => { this.changed.emit(content); }); if (this.initialContent) { this.input = this.initialContent; this.search.next(this.input); } } }
styleUrls: ['./clipboard-paste-textarea.component.scss'] })
random_line_split
clipboard-paste-textarea.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Subject } from 'rxjs/Subject'; function onlyUnique(value, index, self): boolean { return self.indexOf(value) === index; } @Component({ selector: 'app-clipboard-paste-textarea', templateUrl: './clipboard-paste-textarea.component.html', styleUrls: ['./clipboard-paste-textarea.component.scss'] }) export class ClipboardPasteTextareaComponent implements OnInit { @Input() initialContent: string = ''; @Input() placeholder: string = 'paste stuff here'; @Input() distinctLines: boolean = false; @Output() changed = new EventEmitter(); search = new Subject<string>(); input: string = ''; constructor() { } ngOnInit()
}
{ this.search .debounceTime(300) // wait for 300ms pause in events .distinctUntilChanged() // ignore if next search term is same as previous .map(text => text.split('\n').filter(str => str)) .map(lines => this.distinctLines ? lines.filter(onlyUnique) : lines) .subscribe(content => { this.changed.emit(content); }); if (this.initialContent) { this.input = this.initialContent; this.search.next(this.input); } }
identifier_body
clipboard-paste-textarea.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { Subject } from 'rxjs/Subject'; function onlyUnique(value, index, self): boolean { return self.indexOf(value) === index; } @Component({ selector: 'app-clipboard-paste-textarea', templateUrl: './clipboard-paste-textarea.component.html', styleUrls: ['./clipboard-paste-textarea.component.scss'] }) export class ClipboardPasteTextareaComponent implements OnInit { @Input() initialContent: string = ''; @Input() placeholder: string = 'paste stuff here'; @Input() distinctLines: boolean = false; @Output() changed = new EventEmitter(); search = new Subject<string>(); input: string = ''; constructor() { } ngOnInit() { this.search .debounceTime(300) // wait for 300ms pause in events .distinctUntilChanged() // ignore if next search term is same as previous .map(text => text.split('\n').filter(str => str)) .map(lines => this.distinctLines ? lines.filter(onlyUnique) : lines) .subscribe(content => { this.changed.emit(content); }); if (this.initialContent)
} }
{ this.input = this.initialContent; this.search.next(this.input); }
conditional_block
rest-api.service.ts
import * as angular from 'angular'; import { SessionService } from '../session.service'; export class RestApiService { static $inject: string[] = ['$http', 'sessionService']; constructor(private $http: angular.IHttpService, private sessionService: SessionService) { } get<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('GET', url, data); } post<T>(url: string, data?: any): angular.IPromise<T>
delete<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('DELETE', url, data); } private send<T>(method: string, url: string, data: any): angular.IPromise<T> { return this.sessionService.getSession() .then(session => { const httpConfig = { method, url, data, headers: { Authorization: 'Bearer ' + session.accessToken() }}; return this.$http<T>(httpConfig); }).then(arg => { return arg.status === 204 ? null : arg.data; }); } }
{ return this.send<T>('POST', url, data); }
identifier_body
rest-api.service.ts
import * as angular from 'angular'; import { SessionService } from '../session.service'; export class RestApiService { static $inject: string[] = ['$http', 'sessionService']; constructor(private $http: angular.IHttpService, private sessionService: SessionService) { } get<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('GET', url, data); } post<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('POST', url, data); } delete<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('DELETE', url, data); } private
<T>(method: string, url: string, data: any): angular.IPromise<T> { return this.sessionService.getSession() .then(session => { const httpConfig = { method, url, data, headers: { Authorization: 'Bearer ' + session.accessToken() }}; return this.$http<T>(httpConfig); }).then(arg => { return arg.status === 204 ? null : arg.data; }); } }
send
identifier_name
rest-api.service.ts
import * as angular from 'angular'; import { SessionService } from '../session.service'; export class RestApiService { static $inject: string[] = ['$http', 'sessionService']; constructor(private $http: angular.IHttpService, private sessionService: SessionService) { } get<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('GET', url, data); } post<T>(url: string, data?: any): angular.IPromise<T> { return this.send<T>('POST', url, data); }
return this.send<T>('DELETE', url, data); } private send<T>(method: string, url: string, data: any): angular.IPromise<T> { return this.sessionService.getSession() .then(session => { const httpConfig = { method, url, data, headers: { Authorization: 'Bearer ' + session.accessToken() }}; return this.$http<T>(httpConfig); }).then(arg => { return arg.status === 204 ? null : arg.data; }); } }
delete<T>(url: string, data?: any): angular.IPromise<T> {
random_line_split
test_chart_title01.py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class
(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_title01.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of an XlsxWriter file with default title.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [46165376, 54462720] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({'values': '=Sheet1!$A$1:$A$5', 'name': 'Foo'}) chart.set_title({'none': True}) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
identifier_name
test_chart_title01.py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest):
""" Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_title01.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of an XlsxWriter file with default title.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [46165376, 54462720] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({'values': '=Sheet1!$A$1:$A$5', 'name': 'Foo'}) chart.set_title({'none': True}) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
identifier_body
test_chart_title01.py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_title01.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of an XlsxWriter file with default title.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [46165376, 54462720] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5', 'name': 'Foo'}) chart.set_title({'none': True}) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
random_line_split
mail.py
#http://stackoverflow.com/questions/882712/sending-html-email-using-python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class MailAgent(object): """docstring for MailAgent""" def __init__(self, mail, smtp, pseudo, passw):
def send(self, dest, object, text): # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = self.mail msg['To'] = dest # Create the body of the message (a plain-text and an HTML version). html = "<html><head></head><body>{0}</body></html>".format(text) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail = smtplib.SMTP(self.smtp, 587) mail.ehlo() mail.starttls() mail.login(self.pseudo, self.passw) mail.sendmail(self.mail, dest, msg.as_string()) mail.quit()
super(MailAgent, self).__init__() self.mail = mail self.smtp = smtp self.pseudo = pseudo self.passw = passw
identifier_body
mail.py
#http://stackoverflow.com/questions/882712/sending-html-email-using-python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class MailAgent(object): """docstring for MailAgent""" def __init__(self, mail, smtp, pseudo, passw): super(MailAgent, self).__init__() self.mail = mail self.smtp = smtp self.pseudo = pseudo self.passw = passw def send(self, dest, object, text): # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = self.mail msg['To'] = dest # Create the body of the message (a plain-text and an HTML version). html = "<html><head></head><body>{0}</body></html>".format(text) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail = smtplib.SMTP(self.smtp, 587) mail.ehlo() mail.starttls() mail.login(self.pseudo, self.passw)
mail.sendmail(self.mail, dest, msg.as_string()) mail.quit()
random_line_split
mail.py
#http://stackoverflow.com/questions/882712/sending-html-email-using-python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class MailAgent(object): """docstring for MailAgent""" def
(self, mail, smtp, pseudo, passw): super(MailAgent, self).__init__() self.mail = mail self.smtp = smtp self.pseudo = pseudo self.passw = passw def send(self, dest, object, text): # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = "Link" msg['From'] = self.mail msg['To'] = dest # Create the body of the message (a plain-text and an HTML version). html = "<html><head></head><body>{0}</body></html>".format(text) # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Attach parts into message container. # According to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via local SMTP server. mail = smtplib.SMTP(self.smtp, 587) mail.ehlo() mail.starttls() mail.login(self.pseudo, self.passw) mail.sendmail(self.mail, dest, msg.as_string()) mail.quit()
__init__
identifier_name
win32spawn.py
import os import threading import Queue # Windows import import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = False self.wake_up_event = win32event.CreateEvent(None, 0, 0, None) exec_dir = os.getcwd() comspec = os.environ.get("COMSPEC", "cmd.exe") cmd = comspec + ' /c ' + cmd win32event.ResetEvent(self.wake_up_event) currproc = win32api.GetCurrentProcess() sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = 1 child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0) child_stdout_rd_dup = win32api.DuplicateHandle(currproc, child_stdout_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdout_rd) child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0) child_stderr_rd_dup = win32api.DuplicateHandle(currproc, child_stderr_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stderr_rd) child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0) child_stdin_wr_dup = win32api.DuplicateHandle(currproc, child_stdin_wr, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdin_wr) startup_info = win32process.STARTUPINFO() startup_info.hStdInput = child_stdin_rd startup_info.hStdOutput = child_stdout_wr startup_info.hStdError = child_stderr_wr startup_info.dwFlags = win32process.STARTF_USESTDHANDLES cr_flags = 0 cr_flags = win32process.CREATE_NEW_PROCESS_GROUP env = os.environ.copy() self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir), startup_info) win32api.CloseHandle(h_thread) win32file.CloseHandle(child_stdin_rd) win32file.CloseHandle(child_stdout_wr) win32file.CloseHandle(child_stderr_wr) self.__child_stdout = child_stdout_rd_dup self.__child_stderr = child_stderr_rd_dup self.__child_stdin = child_stdin_wr_dup self.exit_code = -1 def close(self): win32file.CloseHandle(self.__child_stdout) win32file.CloseHandle(self.__child_stderr) win32file.CloseHandle(self.__child_stdin) win32api.CloseHandle(self.h_process) win32api.CloseHandle(self.wake_up_event) def kill_subprocess(): win32event.SetEvent(self.wake_up_event) def sleep(secs): win32event.ResetEvent(self.wake_up_event) timeout = int(1000 * secs) val = win32event.WaitForSingleObject(self.wake_up_event, timeout) if val == win32event.WAIT_TIMEOUT: return True else: # The wake_up_event must have been signalled return False def get(self, block=True, timeout=None): return self.queue.get(block=block, timeout=timeout) def qsize(self): return self.queue.qsize() def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: # block waiting for the process to finish or the interrupt to happen handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len(handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: # the process has ended naturally return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects" # Wait for job to finish. Since this method blocks, it can to be called from another thread. # If the application wants to kill the process, it should call kill_subprocess(). def wait(self): if not self.__wait_for_child(): # it's been killed result = False else: # normal termination self.exit_code = win32process.GetExitCodeProcess(self.h_process) result = self.exit_code == 0 self.close() self.is_terminated = True return result # This method gets called on a worker thread to read from either a stderr # or stdout thread from the child process. def __do_read(self, handle): bytesToRead = 1024 while 1: try: finished = 0 hr, data = win32file.ReadFile(handle, bytesToRead, None) if data:
except win32api.error: finished = 1 if finished: return def start_pipe(self): def worker(pipe): return pipe.wait() thrd = threading.Thread(target=worker, args=(self, )) thrd.start()
self.queue.put_nowait(data)
conditional_block
win32spawn.py
import os import threading import Queue # Windows import import win32file import win32pipe import win32api import win32con import win32security import win32process import win32event class Win32Spawn(object): def __init__(self, cmd, shell=False): self.queue = Queue.Queue() self.is_terminated = False self.wake_up_event = win32event.CreateEvent(None, 0, 0, None) exec_dir = os.getcwd() comspec = os.environ.get("COMSPEC", "cmd.exe") cmd = comspec + ' /c ' + cmd win32event.ResetEvent(self.wake_up_event) currproc = win32api.GetCurrentProcess() sa = win32security.SECURITY_ATTRIBUTES() sa.bInheritHandle = 1 child_stdout_rd, child_stdout_wr = win32pipe.CreatePipe(sa, 0) child_stdout_rd_dup = win32api.DuplicateHandle(currproc, child_stdout_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdout_rd) child_stderr_rd, child_stderr_wr = win32pipe.CreatePipe(sa, 0) child_stderr_rd_dup = win32api.DuplicateHandle(currproc, child_stderr_rd, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stderr_rd) child_stdin_rd, child_stdin_wr = win32pipe.CreatePipe(sa, 0) child_stdin_wr_dup = win32api.DuplicateHandle(currproc, child_stdin_wr, currproc, 0, 0, win32con.DUPLICATE_SAME_ACCESS) win32file.CloseHandle(child_stdin_wr) startup_info = win32process.STARTUPINFO() startup_info.hStdInput = child_stdin_rd startup_info.hStdOutput = child_stdout_wr startup_info.hStdError = child_stderr_wr startup_info.dwFlags = win32process.STARTF_USESTDHANDLES cr_flags = 0 cr_flags = win32process.CREATE_NEW_PROCESS_GROUP env = os.environ.copy() self.h_process, h_thread, dw_pid, dw_tid = win32process.CreateProcess(None, cmd, None, None, 1, cr_flags, env, os.path.abspath(exec_dir), startup_info) win32api.CloseHandle(h_thread) win32file.CloseHandle(child_stdin_rd) win32file.CloseHandle(child_stdout_wr) win32file.CloseHandle(child_stderr_wr) self.__child_stdout = child_stdout_rd_dup self.__child_stderr = child_stderr_rd_dup self.__child_stdin = child_stdin_wr_dup self.exit_code = -1 def close(self): win32file.CloseHandle(self.__child_stdout) win32file.CloseHandle(self.__child_stderr) win32file.CloseHandle(self.__child_stdin) win32api.CloseHandle(self.h_process) win32api.CloseHandle(self.wake_up_event) def kill_subprocess(): win32event.SetEvent(self.wake_up_event) def sleep(secs): win32event.ResetEvent(self.wake_up_event) timeout = int(1000 * secs) val = win32event.WaitForSingleObject(self.wake_up_event, timeout) if val == win32event.WAIT_TIMEOUT: return True else: # The wake_up_event must have been signalled return False def get(self, block=True, timeout=None): return self.queue.get(block=block, timeout=timeout) def qsize(self): return self.queue.qsize() def __wait_for_child(self): # kick off threads to read from stdout and stderr of the child process threading.Thread(target=self.__do_read, args=(self.__child_stdout, )).start() threading.Thread(target=self.__do_read, args=(self.__child_stderr, )).start() while True: # block waiting for the process to finish or the interrupt to happen handles = (self.wake_up_event, self.h_process) val = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE) if val >= win32event.WAIT_OBJECT_0 and val < win32event.WAIT_OBJECT_0 + len(handles): handle = handles[val - win32event.WAIT_OBJECT_0] if handle == self.wake_up_event: win32api.TerminateProcess(self.h_process, 1) win32event.ResetEvent(self.wake_up_event) return False elif handle == self.h_process: # the process has ended naturally return True else: assert False, "Unknown handle fired" else: assert False, "Unexpected return from WaitForMultipleObjects" # Wait for job to finish. Since this method blocks, it can to be called from another thread. # If the application wants to kill the process, it should call kill_subprocess(). def wait(self): if not self.__wait_for_child(): # it's been killed result = False else: # normal termination self.exit_code = win32process.GetExitCodeProcess(self.h_process) result = self.exit_code == 0 self.close() self.is_terminated = True return result # This method gets called on a worker thread to read from either a stderr # or stdout thread from the child process. def __do_read(self, handle): bytesToRead = 1024 while 1: try: finished = 0 hr, data = win32file.ReadFile(handle, bytesToRead, None) if data: self.queue.put_nowait(data) except win32api.error: finished = 1 if finished: return def start_pipe(self):
def worker(pipe): return pipe.wait() thrd = threading.Thread(target=worker, args=(self, )) thrd.start()
identifier_body