file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
focusevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::...
// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
{ self.related_target.get() }
identifier_body
karma.conf.js
var path = require('path') var configVars = require('./configVars.js') var karmaConfig = { basePath: './', frameworks: ['jasmine-jquery', 'jasmine'], port: 9876, colors: true, autoWatch: false, browsers: ['PhantomJS'], singleRun: true, concurrency: 1, files: [ './' + configVars['unitTests']['entry...
test: /\.js$/, loader: 'babel' }, { test: /^(.(?!\.spec))*\.js$/, include: path.resolve('./' + configVars['js']['srcPath']), loader: 'isparta' } ] }, externals: [ {} ], cache: true } } karmaConfig.preprocessors['./' ...
{
random_line_split
test_sqlite.js
var fs = require('fs'); var daff = require('daff'); var assert = require('assert'); var Fiber = null; var sqlite3 = null; try { Fiber = require('fibers'); sqlite3 = require('sqlite3'); } catch (err) { // We don't have what we need for accessing the sqlite database. // Not an error. console.log("No ...
['---', 1, 'Paul']]); assert(target.isSimilar(out)); }).run();
['->', 2, 'Naomi->Noemi'],
random_line_split
index.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } #[cfg(test)] mod tests { use super::*; use serde_json; #[test] fn block_number_deserialization() { let s = r#"["0xa", "10"]"#; let deserialized: Vec<Index...
visit_string
identifier_name
index.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } #[cfg(test)] mod tests { use super::*; use serde_json; #[test] fn block_number_deserialization() { let s = r#"["0xa", "10"]"#; let de...
{ match value { _ if value.starts_with("0x") => usize::from_str_radix(&value[2..], 16).map(Index).map_err(|_| Error::custom("invalid index")), _ => value.parse::<usize>().map(Index).map_err(|_| Error::custom("invalid index")), } }
identifier_body
index.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
where E: Error, { self.visit_str(value.as_ref()) } } #[cfg(test)] mod tests { use super::*; use serde_json; #[test] fn block_number_deserialization() { let s = r#"["0xa", "10"]"#; let deserialized: Vec<Index> = serde_json::from_str(s).unwrap(); asser...
random_line_split
snapshot.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/. */ //! A gecko snapshot, that stores the element attributes and state before they //! change in order to properly cal...
(&self) -> String { use nsstring::nsCString; let mut string = nsCString::new(); unsafe { bindings::Gecko_Snapshot_DebugListAttributes(self, &mut string); } String::from_utf8_lossy(&*string).into_owned() } fn state(&self) -> Option<ElementState> { if s...
debug_list_attributes
identifier_name
snapshot.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/. */ //! A gecko snapshot, that stores the element attributes and state before they //! change in order to properly cal...
CaseSensitivity::CaseSensitive => false, CaseSensitivity::AsciiCaseInsensitive => true, }; // FIXME: case sensitivity for operators other than Equal match operator { AttrSelectorOperator::...
random_line_split
snapshot.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/. */ //! A gecko snapshot, that stores the element attributes and state before they //! change in order to properly cal...
local_name.as_ptr(), expected_value.as_ptr(), ignore_case, ), AttrSelectorOperator::Includes => bindings::Gecko_SnapshotAttrIncludes( self, ...
{ unsafe { match *operation { AttrSelectorOperation::Exists => { bindings::Gecko_SnapshotHasAttr(self, ns.atom_or_null(), local_name.as_ptr()) }, AttrSelectorOperation::WithValue { operator, c...
identifier_body
Sc-code-points.js
// All code points in the `Sc` category as per Unicode v6.3.0: [ 0x24, 0xA2, 0xA3,
0xA4, 0xA5, 0x58F, 0x60B, 0x9F2, 0x9F3, 0x9FB, 0xAF1, 0xBF9, 0xE3F, 0x17DB, 0x20A0, 0x20A1, 0x20A2, 0x20A3, 0x20A4, 0x20A5, 0x20A6, 0x20A7, 0x20A8, 0x20A9, 0x20AA, 0x20AB, 0x20AC, 0x20AD, 0x20AE, 0x20AF, 0x20B0, 0x20B1, 0x20B2, 0x20B3, 0x20B4, 0x20B5, 0x20B6, 0x20B7, 0x20B8, 0x20B9,...
random_line_split
react-native.ts
import { GluegunToolbox } from "gluegun" import { children } from "./filesystem-ext" export const isAndroidInstalled = (toolbox: GluegunToolbox): boolean => { const androidHome = process.env.ANDROID_HOME const hasAndroidEnv = !toolbox.strings.isBlank(androidHome) const hasAndroid = hasAndroidEnv && toolbox.files...
(toolbox: GluegunToolbox, options: CopyBoilerplateOptions) { const { filesystem } = toolbox const { copyAsync, path } = filesystem // ensure the desitnation folder exists await filesystem.dirAsync(options.projectName) // rather than copying everything wholesale, let's check what's in the boilerplate folder ...
copyBoilerplate
identifier_name
react-native.ts
import { GluegunToolbox } from "gluegun" import { children } from "./filesystem-ext" export const isAndroidInstalled = (toolbox: GluegunToolbox): boolean => { const androidHome = process.env.ANDROID_HOME const hasAndroidEnv = !toolbox.strings.isBlank(androidHome) const hasAndroid = hasAndroidEnv && toolbox.files...
copyAsync(path(options.boilerplatePath, fileOrFolder), path(options.projectName, fileOrFolder)), ) // copy them all at once return Promise.all(copyPromises) }
{ const { filesystem } = toolbox const { copyAsync, path } = filesystem // ensure the desitnation folder exists await filesystem.dirAsync(options.projectName) // rather than copying everything wholesale, let's check what's in the boilerplate folder // and copy over everything except stuff like lockfiles a...
identifier_body
react-native.ts
import { GluegunToolbox } from "gluegun" import { children } from "./filesystem-ext" export const isAndroidInstalled = (toolbox: GluegunToolbox): boolean => { const androidHome = process.env.ANDROID_HOME const hasAndroidEnv = !toolbox.strings.isBlank(androidHome) const hasAndroid = hasAndroidEnv && toolbox.files...
// copy them all at once return Promise.all(copyPromises) }
random_line_split
cache.py
#!/usr/bin/env python #-*- coding: utf8 -*- # Copyright 2009-2012 Kamil Winczek <kwinczek@gmail.com> # # This file is part of series.py. # # series.py is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either ve...
import time import tvs.show # Spinner implementation. @contextlib.contextmanager def spinning_distraction(spin): if spin: global p p = subprocess.Popen(['tvs_spin.py']) yield p.terminate() sys.stdout.write("\r") sys.stdout.flush() else: yield # -----...
try: import urllib2 except ImportError: import urllib as urllib2
random_line_split
cache.py
#!/usr/bin/env python #-*- coding: utf8 -*- # Copyright 2009-2012 Kamil Winczek <kwinczek@gmail.com> # # This file is part of series.py. # # series.py is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either ve...
def __get_show_id(self): """Returns first found id from search list. """ # Try to get id from ids cache file if self.options.cache and not self.options.refresh: showid = self.__get_id_from_cache() if not showid: showid = self.__get_id_from_tvrage() ...
try: with spinning_distraction(spin=self.options.spinner): return tvs.show.Show(etree.fromstring(urllib2.urlopen(self.url_full_show).read()), self.options) except KeyboardInterrupt: raise except: return None
identifier_body
cache.py
#!/usr/bin/env python #-*- coding: utf8 -*- # Copyright 2009-2012 Kamil Winczek <kwinczek@gmail.com> # # This file is part of series.py. # # series.py is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either ve...
else: return showid elif self.options.refresh: showid = self.__get_id_from_tvrage() if showid: self.__save_id_to_cache(showid) return showid elif not self.options.cache: return self.__get_id_from_tvrage() ...
showid = self.__get_id_from_tvrage() if showid: self.__save_id_to_cache(showid) return showid return showid
conditional_block
cache.py
#!/usr/bin/env python #-*- coding: utf8 -*- # Copyright 2009-2012 Kamil Winczek <kwinczek@gmail.com> # # This file is part of series.py. # # series.py is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either ve...
(self): """If cache was used all files need to be closed.""" if self.options.cache: self.c.close() self.i.close() def __save_id_to_cache(self, showid): """Saves retrieved show's id to cache""" self.i[self.keyword] = showid def __save_show_to_cache(self...
__del__
identifier_name
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2011 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.xmlstream import StanzaBase, ElementBase class STARTTLS(ElementBase): """ """ name = 'starttls' namespace = '...
""" """ name = 'failure' namespace = 'urn:ietf:params:xml:ns:xmpp-tls' interfaces = set()
identifier_body
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2011 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.xmlstream import StanzaBase, ElementBase class STARTTLS(ElementBase): """ """ name = 'starttls' namespace = '...
return True class Proceed(StanzaBase): """ """ name = 'proceed' namespace = 'urn:ietf:params:xml:ns:xmpp-tls' interfaces = set() class Failure(StanzaBase): """ """ name = 'failure' namespace = 'urn:ietf:params:xml:ns:xmpp-tls' interfaces = set()
plugin_attrib = name def get_required(self): """ """
random_line_split
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2011 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.xmlstream import StanzaBase, ElementBase class
(ElementBase): """ """ name = 'starttls' namespace = 'urn:ietf:params:xml:ns:xmpp-tls' interfaces = set(('required',)) plugin_attrib = name def get_required(self): """ """ return True class Proceed(StanzaBase): """ """ name = 'proceed' namespace...
STARTTLS
identifier_name
initrd.rs
//! Initial ramdisk driver use alloc::string::String; use alloc::vec::Vec; use hashbrown::HashMap; use x86_64::{PhysAddr, VirtAddr}; use d7initrd::{FileEntry, HEADER_MAGIC, HEADER_SIZE_BYTES}; use crate::memory::{self, phys_to_virt, prelude::*}; use crate::util::elf_parser::{self, ELFData, ELFHeader, ELFProgramHeade...
/// Files by name. files: HashMap<String, FileEntry>, /// A slice containing all files, concatenated. /// The lifetime is static, as these are never deallocated. slice: &'static [u8], } static INITRD: spin::Once<InitRD> = spin::Once::new(); pub fn init(elf_data: ELFData) { unsafe { // ...
#[derive(Debug)] struct InitRD {
random_line_split
initrd.rs
//! Initial ramdisk driver use alloc::string::String; use alloc::vec::Vec; use hashbrown::HashMap; use x86_64::{PhysAddr, VirtAddr}; use d7initrd::{FileEntry, HEADER_MAGIC, HEADER_SIZE_BYTES}; use crate::memory::{self, phys_to_virt, prelude::*}; use crate::util::elf_parser::{self, ELFData, ELFHeader, ELFProgramHeade...
(elf_data: ELFData) { unsafe { // Get address let start_addr = PhysAddr::from_u64(page_align_up(elf_data.last_addr())); let header = phys_to_virt(start_addr); let hptr: *const u8 = header.as_ptr(); let magic = *(hptr.add(0) as *const u32); let size_flist = *(hptr.add...
init
identifier_name
initrd.rs
//! Initial ramdisk driver use alloc::string::String; use alloc::vec::Vec; use hashbrown::HashMap; use x86_64::{PhysAddr, VirtAddr}; use d7initrd::{FileEntry, HEADER_MAGIC, HEADER_SIZE_BYTES}; use crate::memory::{self, phys_to_virt, prelude::*}; use crate::util::elf_parser::{self, ELFData, ELFHeader, ELFProgramHeade...
{ let rd: &InitRD = INITRD.poll().unwrap(); log::trace!("Read {:?} (found={})", name, rd.files.contains_key(name)); let entry = rd.files.get(name)?; let start = entry.offset as usize; let len = entry.size as usize; Some(&rd.slice[start..start + len]) }
identifier_body
OrgLDIF.py
# -*- coding: utf-8 -*- # # Copyright 2004-2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
self.person_titles[emp['person_id']] = title timer("...personal employment titles done.")
'Fetching personal employment titles...') employments = self.person.search_employment(main_employment=True) for emp in employments: if emp['person_id'] not in self.person_titles: title = [(self.const.language_nb, emp['description'])]
random_line_split
OrgLDIF.py
# -*- coding: utf-8 -*- # # Copyright 2004-2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
(self, *args, **kwargs): super(OrgLDIFHiAMixin, self).__init__(*args, **kwargs) self.attr2syntax['mobile'] = self.attr2syntax['telephoneNumber'] self.attr2syntax['roomNumber'] = (None, None, normalize_string) def init_attr2id2contacts(self): # Changes from the original: # - ...
__init__
identifier_name
OrgLDIF.py
# -*- coding: utf-8 -*- # # Copyright 2004-2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
return dict((key, attr_unique(values, normalize=normalize)) for key, values in cont_tab.iteritems()) def init_person_titles(self): """Extends the person_titles dict with employment titles available via the PersonEmployment module.""" super(OrgLDIFHiAMixin, self...
alias = convert(text_type(row['contact_alias'])) if alias and verify(alias): cont_tab[int(row['entity_id'])].append(alias)
conditional_block
OrgLDIF.py
# -*- coding: utf-8 -*- # # Copyright 2004-2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # ...
('telephoneNumber', manual, self.const.contact_phone), ('facsimileTelephoneNumber', manual, self.const.contact_fax), ('mobile', sap, self.const.contact_mobile_phone), ('labeledURI', None, self.const.contact_url))] self.id2labeledURI = contacts[-1]...
"""Mixin class for norEduLDIFMixin(OrgLDIF) with HiA modifications.""" def __init__(self, *args, **kwargs): super(OrgLDIFHiAMixin, self).__init__(*args, **kwargs) self.attr2syntax['mobile'] = self.attr2syntax['telephoneNumber'] self.attr2syntax['roomNumber'] = (None, None, normalize_string)...
identifier_body
tools.py
jinja2.filters import FILTERS import os import maraschino from maraschino import app, logger from maraschino.models import Setting, XbmcServer from flask import send_file import StringIO import urllib import re def check_auth(username, password): """This function is called to check if a username / password co...
if version == 'eden': url = '%s/vfs/special://%s' % (xbmc_url, url) elif version == 'frodo': url = '%s/image/image://%s' % (xbmc_url, urllib.quote(url.encode('utf-8'), '')) img = StringIO.StringIO(urllib.urlopen(url).read()) return send_file(img, mimetype='image/jpeg') def youtube_to_...
else: xbmc_url = server_address()
random_line_split
tools.py
jinja2.filters import FILTERS import os import maraschino from maraschino import app, logger from maraschino.models import Setting, XbmcServer from flask import send_file import StringIO import urllib import re def check_auth(username, password): """This function is called to check if a username / password co...
elif prepend_path_minus_root: full = os.path.join(root, file) partial = full.replace(folder, '') if partial.startswith('/'): partial = partial.replace('/', '', 1) elif partial.startswith('\\'): ...
filelist.append(os.path.join(root,file))
conditional_block
tools.py
jinja2.filters import FILTERS import os import maraschino from maraschino import app, logger from maraschino.models import Setting, XbmcServer from flask import send_file import StringIO import urllib import re def check_auth(username, password): """This function is called to check if a username / password co...
(num): if (num > 0): return int(num+.5) else: return int(num-.5) FILTERS['round_number'] = round_number def format_number(num): extension_list = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'] for i in range(len(extension_list)): base = 1024**i if num/base < 1024: ...
round_number
identifier_name
tools.py
jinja2.filters import FILTERS import os import maraschino from maraschino import app, logger from maraschino.models import Setting, XbmcServer from flask import send_file import StringIO import urllib import re def check_auth(username, password): """This function is called to check if a username / password co...
return decorated def using_auth(): """Check if authentication is necessary""" if maraschino.AUTH['username'] != None and maraschino.AUTH['password'] != None: return True else: return False def format_time(time): """Format the time for the player info""" formatted_time = '' ...
if maraschino.AUTH['username'] != None and maraschino.AUTH['password'] != None: creds = maraschino.AUTH else: return f(*args, **kwargs) auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() r...
identifier_body
apiInterfaces.js
var http = require('http'); function jsonHttpRequest(host, port, data, callback){ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', ...
var data = JSON.stringify(rpcArray); jsonHttpRequest(host, port, data, callback); } module.exports = function(daemonConfig, walletConfig){ return { batchRpcDaemon: function(batchArray, callback){ batchRpc(daemonConfig.host, daemonConfig.port, batchArray, callback); }, ...
{ rpcArray.push({ id: i.toString(), jsonrpc: "2.0", method: array[i][0], params: array[i][1] }); }
conditional_block
apiInterfaces.js
var http = require('http'); function
(host, port, data, callback){ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', 'Accept': 'application/json' } }; v...
jsonHttpRequest
identifier_name
apiInterfaces.js
var http = require('http'); function jsonHttpRequest(host, port, data, callback)
res.on('end', function(){ var replyJson; try{ replyJson = JSON.parse(replyData); } catch(e){ callback(e); return; } callback(null, replyJson); }); }); req.on('error', function...
{ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', 'Accept': 'application/json' } }; var req = http.request(option...
identifier_body
apiInterfaces.js
var http = require('http'); function jsonHttpRequest(host, port, data, callback){ var options = { hostname: host, port: port, path: '/json_rpc', method: 'POST', headers: { 'Content-Length': data.length, 'Content-Type': 'application/json', ...
catch(e){ callback(e); return; } callback(null, replyJson); }); }); req.on('error', function(e){ callback(e); }); req.end(data); } function rpc(host, port, method, params, callback){ var data = JSON.stringify({ ...
var replyJson; try{ replyJson = JSON.parse(replyData); }
random_line_split
urls.py
# 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/. from django.conf.urls import patterns, url from oneanddone.users import views urlpatterns = patterns('', url(r'^lo...
# API URL's for interacting with User objects url(r'^api/v1/user/$', views.UserListAPI.as_view(), name='api-user'), url(r'^api/v1/user/(?P<email>[^/\\]+)/$', views.UserDetailAPI.as_view(), name='api-user-detail'), )
random_line_split
issue-49579.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn fibs(n: u32) -> impl Iterator<Item=u128> { (0 .. n) .scan((0, 1), |st, _| { *st = (st.1, st.0 + st.1); Some(*st) }) .map(&|(f, _)| f) } fn main() { println!("{:?}", fibs(10).collect::<Vec<_>>()); }
// ignore-emscripten no i128 support #![feature(nll)]
random_line_split
issue-49579.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { println!("{:?}", fibs(10).collect::<Vec<_>>()); }
{ (0 .. n) .scan((0, 1), |st, _| { *st = (st.1, st.0 + st.1); Some(*st) }) .map(&|(f, _)| f) }
identifier_body
issue-49579.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { println!("{:?}", fibs(10).collect::<Vec<_>>()); }
main
identifier_name
icon_importer.py
_data() if not image: image, image_file, icon_url = self.fetch_image_from_path(force=self.force) if image: image = self.normalize_image(image) try: color = self.determine_dominant_color_in_image(image) except IndexError: re...
def get_image_from_url(self, url): # print 'Requesting: %s' % url if not url: return None, None @timelimit(30) def _1(url): headers = { 'User-Agent': 'NewsBlur Favicon Fetcher - %s subscriber%s - %s ' '(Mozilla/...
image = None url = None if not force: url = self.feed_icon.icon_url if not url and self.feed.feed_link and len(self.feed.feed_link) > 6: try: url = urlparse.urljoin(self.feed.feed_link, 'favicon.ico') except ValueError: url = N...
identifier_body
icon_importer.py
_data() if not image: image, image_file, icon_url = self.fetch_image_from_path(force=self.force) if image: image = self.normalize_image(image) try: color = self.determine_dominant_color_in_image(image) except IndexError: re...
(self, content): url = None if not content: return url try: if isinstance(content, unicode):
_url_from_html
identifier_name
icon_importer.py
_data() if not image:
color = self.determine_dominant_color_in_image(image) except IndexError: return try: image_str = self.string_from_image(image) except TypeError: return if len(image_str) > 500000: image = Non...
image, image_file, icon_url = self.fetch_image_from_path(force=self.force) if image: image = self.normalize_image(image) try:
random_line_split
icon_importer.py
_data() if not image: image, image_file, icon_url = self.fetch_image_from_path(force=self.force) if image: image = self.normalize_image(image) try: color = self.determine_dominant_color_in_image(image) except IndexError: re...
else: # Patch up the bitmap height image.size = image.size[0], image.size[1] >> 1 d, e, o, a = image.tile[0] image.tile[0] = d, (0, 0) + image.size, o, a # Calculate AND bitmap dimensions. See # http://en.wikip...
pass
conditional_block
test_rerun.py
# -*- encoding: utf-8 -*- from mock import Mock, patch from psutil import AccessDenied, TimeoutExpired from thefuck.output_readers import rerun class TestRerun(object): def setup_method(self, test_method): self.patcher = patch('thefuck.output_readers.rerun.Process') process_mock = self.patcher.s...
elf, logs_mock): proc = Mock() proc.kill.side_effect = AccessDenied() rerun._kill_process(proc) proc.kill.assert_called_once_with() logs_mock.debug.assert_called_once()
st_kill_process_access_denied(s
identifier_name
test_rerun.py
# -*- encoding: utf-8 -*- from mock import Mock, patch from psutil import AccessDenied, TimeoutExpired from thefuck.output_readers import rerun class TestRerun(object): def setup_method(self, test_method): self.patcher = patch('thefuck.output_readers.rerun.Process') process_mock = self.patcher.s...
@patch('thefuck.output_readers.rerun._wait_output', return_value=False) @patch('thefuck.output_readers.rerun.Popen') def test_get_output(self, popen_mock, wait_output_mock): popen_mock.return_value.stdout.read.return_value = b'output' assert rerun.get_output('', '') is None wait_ou...
self.patcher.stop()
identifier_body
test_rerun.py
# -*- encoding: utf-8 -*- from mock import Mock, patch from psutil import AccessDenied, TimeoutExpired from thefuck.output_readers import rerun class TestRerun(object): def setup_method(self, test_method): self.patcher = patch('thefuck.output_readers.rerun.Process') process_mock = self.patcher.s...
def test_wait_output_is_not_slow(self, settings): assert rerun._wait_output(Mock(), False) self.proc_mock.wait.assert_called_once_with(settings.wait_command) @patch('thefuck.output_readers.rerun._kill_process') def test_wait_output_timeout(self, kill_process_mock): self.proc_mock.w...
def test_wait_output_is_slow(self, settings): assert rerun._wait_output(Mock(), True) self.proc_mock.wait.assert_called_once_with(settings.wait_slow_command)
random_line_split
InfoCircleIcon.tsx
import { useColor } from "palette/hooks" import React from "react" import { Icon, IconProps, Path } from "./Icon" export const InfoCircleIcon: React.FC<IconProps> = (props) => { const color = useColor() return ( <Icon {...props} viewBox="0 0 18 18">
<Path d="M9 1.889A7.111 7.111 0 1 1 9 16.11 7.111 7.111 0 0 1 9 1.89zM9 1a8 8 0 1 0 0 16A8 8 0 0 0 9 1zm-.489 4.133h.978V6.2H8.51V5.133zm.978 2.24v5.494H8.51V7.373h.978z" fill={color(props.fill)} fillRule="nonzero" /> </Icon> ) }
random_line_split
info.js
/*******************************************************************************
* 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. * Se...
* Copyright 2013-2014 Aerospike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
random_line_split
sqlite_extractor.py
import sys, os import toml import pandas as pd import numpy as np from DatabaseExtractor import DatabaseExtractor def
(config): """ Check that the configuration is valid""" ok = True if config['output']['sort_column'] not in config['output']['columns']: print("Sort column not in output columns list") ok = False return ok ########################################################## config = None sqlite_file = None ou...
check_output_config
identifier_name
sqlite_extractor.py
import sys, os import toml import pandas as pd import numpy as np from DatabaseExtractor import DatabaseExtractor def check_output_config(config):
########################################################## config = None sqlite_file = None out_file = None try: config_file = sys.argv[1] with open(config_file, "r") as config_chan: config = toml.loads(config_chan.read()) sqlite_file = sys.argv[2] out_file = sys.argv[3] except IndexError: print("Us...
""" Check that the configuration is valid""" ok = True if config['output']['sort_column'] not in config['output']['columns']: print("Sort column not in output columns list") ok = False return ok
identifier_body
sqlite_extractor.py
import sys, os import toml import pandas as pd import numpy as np from DatabaseExtractor import DatabaseExtractor def check_output_config(config): """ Check that the configuration is valid""" ok = True if config['output']['sort_column'] not in config['output']['columns']: print("Sort column not in output c...
# Write the final CSV all_data.to_csv(out_file, index=False) finally: if extractor is not None: del extractor
for i in range(0, len(all_data[col_map['column']])): if all_data.iloc[i, column_index] not in mapped_values: all_data.iloc[i, column_index] = col_map['other']
random_line_split
sqlite_extractor.py
import sys, os import toml import pandas as pd import numpy as np from DatabaseExtractor import DatabaseExtractor def check_output_config(config): """ Check that the configuration is valid""" ok = True if config['output']['sort_column'] not in config['output']['columns']: print("Sort column not in output c...
# Write the final CSV all_data.to_csv(out_file, index=False) finally: if extractor is not None: del extractor
for col_map in config['column_mapping']['mappings']: mapped_values = [] all_data[col_map['column']] = all_data[col_map['column']].astype(str) for source, dest in col_map['mapping']: all_data[col_map['column']].replace(source, dest, inplace=True) mapped_values.append(dest) col...
conditional_block
parser.py
# parser.py # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY...
return line def _absurl(self, url): """ Returns an absolute url for the (possibly) relative url specified. The base url used to resolve the missing bits of url is the url of the file currently being included (i.e. the top of the stack). """ if len(...
return substitute(line, self._vars)
conditional_block
parser.py
# parser.py # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY...
(self): return self.name
geturl
identifier_name
parser.py
# parser.py # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY...
return self.name
identifier_body
parser.py
# parser.py # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY...
has previously been included. If the file can not be opened this function exits. """ # absolutize this url using the including files url # as a base url. absurl = self._absurl(url) # get the current section to add it to the included # url's name. ...
Opens the url specified, pushes it on the stack, and returns a file like object. Returns None if the url
random_line_split
Tournament.js
i++){ var goodAgent = best[i]; var config = AGENTS.find(function(config){ return config.strategy==goodAgent.strategyName; }); config.count++; // ADD one } // ADD agents, splicing right AFTER for(var i=0; i<best.length; i++){ // Properties... var goodAgent = best[i]; var angle = goodAge...
function TournamentAgent(config){ var self = this; self.strategyName = config.strategy;
random_line_split
Tournament.js
self.connections[0].kill(); // Connect all of 'em for(var i=0; i<self.agents.length; i++){ var playerA = self.agents[i]; var flip = false; for(var j=i+1; j<self.agents.length; j++){ var playerB = self.agents[j]; var connection = new TournamentConnection({ tournament: self, from: playe...
{ // Start if(_tweenTimer==0){ self.reproduceTop(Tournament.SELECTION); } // Middle... _tweenTimer += self.isAutoPlaying ? 0.15 : 0.05; if(_tweenTimer>1) _tweenTimer=1; for(var i=0;i<self.agents.length;i++){ var a = self.agents[i]; a.tweenAngle(_tweenTimer); a.updatePosition(); ...
conditional_block
Tournament.js
(config){ var self = this; self.id = config.id; // APP var app = new PIXI.Application(500, 500, {transparent:true, resolution:2}); self.dom = app.view; // DOM self.dom.className = "object"; self.dom.style.width = 500; self.dom.style.height = 500; self.dom.style.left = config.x+"px"; self.dom.style.top = ...
Tournament
identifier_name
Tournament.js
match[0] && c.to==match[1]) return true; if(c.from==match[1] && c.to==match[0]) return true; return false; })[0]; connection.highlight(); // Actually PLAY the game -- HACK: HARD-CODE 10 ROUNDS var scores = PD.playRepeatedGame(match[0], match[1], 10); // Return ALL this data... return { charA: mat...
{ var self = this; self.config = config; self.tournament = config.tournament; // Connect from & to self.from = config.from; self.to = config.to; self.from.connections.push(self); self.to.connections.push(self); // Graphics! var g; if(Tournament.FLOWER_CONNECTIONS){ g = _makeMovieClip("connection_flower"...
identifier_body
entity.py
.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return self._unique_id @property def zha_device(self) -> ZhaDeviceType: """Return the zha device this entity is attached to.""" return self._zha_device @property def ...
random_line_split
entity.py
_MANUFACTURER, ATTR_MODEL, DATA_ZHA, DATA_ZHA_BRIDGE_ID, DOMAIN, SIGNAL_GROUP_ENTITY_REMOVED, SIGNAL_GROUP_MEMBERSHIP_CHANGE, SIGNAL_REMOVE, ) from .core.helpers import LogMixin from .core.typing import CALLABLE_T, ChannelType, ZhaDeviceType _LOGGER = logging.getLogger(__name__) ENTITY_SUF...
self._unsubs.append(unsub) def log(self, level: int, msg: str, *args): """Log a message.""" msg = f"%s: {msg}" args = (self.entity_id,) + args _LOGGER.log(level, msg, *args) class ZhaEntity(BaseZhaEntity, RestoreEntity): """A base class for non group ZHA entities.""" ...
unsub = async_dispatcher_connect( self.hass, f"{channel.unique_id}_{signal}", func )
conditional_block
entity.py
_MANUFACTURER, ATTR_MODEL, DATA_ZHA, DATA_ZHA_BRIDGE_ID, DOMAIN, SIGNAL_GROUP_ENTITY_REMOVED, SIGNAL_GROUP_MEMBERSHIP_CHANGE, SIGNAL_REMOVE, ) from .core.helpers import LogMixin from .core.typing import CALLABLE_T, ChannelType, ZhaDeviceType _LOGGER = logging.getLogger(__name__) ENTITY_SUF...
@callback def async_state_changed(self) -> None: """Entity state changed.""" self.async_write_ha_state() @callback def async_update_state_attribute(self, key: str, value: Any) -> None: """Update a single device state attribute.""" self._extra_state_attributes.update({k...
"""Return a device description for device registry.""" zha_device_info = self._zha_device.device_info ieee = zha_device_info["ieee"] return entity.DeviceInfo( connections={(CONNECTION_ZIGBEE, ieee)}, identifiers={(DOMAIN, ieee)}, manufacturer=zha_device_info[A...
identifier_body
entity.py
_MANUFACTURER, ATTR_MODEL, DATA_ZHA, DATA_ZHA_BRIDGE_ID, DOMAIN, SIGNAL_GROUP_ENTITY_REMOVED, SIGNAL_GROUP_MEMBERSHIP_CHANGE, SIGNAL_REMOVE, ) from .core.helpers import LogMixin from .core.typing import CALLABLE_T, ChannelType, ZhaDeviceType _LOGGER = logging.getLogger(__name__) ENTITY_SUF...
(self): """Handle group membership changed.""" # Make sure we don't call remove twice as members are removed if self._handled_group_membership: return self._handled_group_membership = True await self.async_remove(force_remove=True) async def async_added_to_hass(...
_handle_group_membership_changed
identifier_name
unboxed-closures-extern-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = call_it(&square, 22); let y = call_it_mut(&mut square, 22); let z = call_it_once(square, 22); assert_eq!(x, square(22)); assert_eq!(y, square(22)); assert_eq!(z, square(22)); }
identifier_body
unboxed-closures-extern-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn square(x: int) -> int { x * x } fn call_it<F:Fn(int)->int>(f: &F, x: int) -> int { f(x) } fn call_it_mut<F:FnMut(int)->int>(f: &mut F, x: int) -> int { f(x) } fn call_it_once<F:FnOnce(int)->int>(f: F, x: int) -> int { f(x) } fn main() { let x = call_it(&square, 22); let y = call_it_mut(&mut s...
#![feature(unboxed_closures)] use std::ops::{Fn,FnMut,FnOnce};
random_line_split
unboxed-closures-extern-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(x: int) -> int { x * x } fn call_it<F:Fn(int)->int>(f: &F, x: int) -> int { f(x) } fn call_it_mut<F:FnMut(int)->int>(f: &mut F, x: int) -> int { f(x) } fn call_it_once<F:FnOnce(int)->int>(f: F, x: int) -> int { f(x) } fn main() { let x = call_it(&square, 22); let y = call_it_mut(&mut square, 22...
square
identifier_name
Drawer.tsx
import React, { CSSProperties, FC, ReactNode, useState } from 'react'; import { GrafanaTheme2 } from '../../../data'; import RcDrawer from 'rc-drawer'; import { css } from '@emotion/css'; import { CustomScrollbar } from '../CustomScrollbar/CustomScrollbar'; import { IconButton } from '../IconButton/IconButton'; import...
margin-bottom: ${theme.spacing(2)}; `, content: css` padding: ${theme.spacing(2)}; flex-grow: 1; overflow: ${!scrollableContent ? 'hidden' : 'auto'}; z-index: 0; height: 100%; `, }; }); export const Drawer: FC<Props> = ({ children, inline = false, onClose, clos...
overflow-wrap: break-word; `, titleSpacing: css`
random_line_split
index.d.ts
* This is primarily for integrating with other libraries that need to participate in rendering before the route components are rendered. It defaults to render={(props) => <RouterContext {...props} />}. * Ensure that you render a <RouterContext> at the end of the line, passing all the props passed to render. */ ...
* Identical to push except replaces the current history entry with a new one. * * @param {LocationDescriptor} pathOrLoc */ replace(pathOrLoc: LocationDescriptor): void; /** * Go forward or backward in the history by n or -n. * * @param {number} n */ go(n: number): void; /** * Go bac...
push(pathOrLoc: LocationDescriptor): void; /**
random_line_split
index.d.ts
Route extends React.Component<IRouteProps, {}> { } export interface PlainRoute extends IRouteProps { /** * An array of child routes, same as children in JSX route configs. * * @type {PlainRoute[]} */ childRoutes?: PlainRoute[]; /** * Same as childRoutes but asynchronous and receives the locatio...
IndexRoute
identifier_name
text_input.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = requi...
function TextInput(props) { _classCallCheck(this, TextInput); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.state = {}; return _this; } TextInput.prototype.hasFocus = function hasFocus() { return this.state.focused; }; TextInput.prototype.rende...
var TextInput = function (_React$Component) { _inherits(TextInput, _React$Component);
random_line_split
text_input.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = requi...
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call...
{ var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
identifier_body
text_input.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = requi...
(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw n...
_possibleConstructorReturn
identifier_name
text_input.js
'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key))
} } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _input_wrap = require('./input_wrap'); var _input_wrap2 = _interopRequireDefault(_input_wrap); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWit...
{ target[key] = source[key]; }
conditional_block
generate_ml_data.py
#!/usr/bin/env python import sct_utils as sct import os #path = '/Users/benjamindeleener/data/data_testing/C2-T2/' contrast = 't2' #path_output_seg = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/labels/' #path_output_im = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/dat...
:return data: """ data_subjects, subjects_dir = [], [] # each directory in folder_dataset should be a directory of a subject for subject_dir in os.listdir(folder_dataset): if not subject_dir.startswith('.') and os.path.isdir(folder_dataset + subject_dir): data_subjects.append(fo...
def generate_data_list(folder_dataset, verbose=1): """ Construction of the data list from the data set This function return a list of directory (in folder_dataset) in which the contrast is present.
random_line_split
generate_ml_data.py
#!/usr/bin/env python import sct_utils as sct import os #path = '/Users/benjamindeleener/data/data_testing/C2-T2/' contrast = 't2' #path_output_seg = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/labels/' #path_output_im = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/dat...
(folder_dataset, verbose=1): """ Construction of the data list from the data set This function return a list of directory (in folder_dataset) in which the contrast is present. :return data: """ data_subjects, subjects_dir = [], [] # each directory in folder_dataset should be a directory of ...
generate_data_list
identifier_name
generate_ml_data.py
#!/usr/bin/env python import sct_utils as sct import os #path = '/Users/benjamindeleener/data/data_testing/C2-T2/' contrast = 't2' #path_output_seg = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/labels/' #path_output_im = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/dat...
data_subjects, subjects_name = generate_data_list(path) current_folder = os.getcwd() for subject_folder in data_subjects: print subject_folder os.chdir(subject_folder+contrast) sct.run('sct_seg_utility.py -i ' + contrast + '.nii.gz' ' -seg ' + contrast + '_manual_seg...
""" Construction of the data list from the data set This function return a list of directory (in folder_dataset) in which the contrast is present. :return data: """ data_subjects, subjects_dir = [], [] # each directory in folder_dataset should be a directory of a subject for subject_dir in ...
identifier_body
generate_ml_data.py
#!/usr/bin/env python import sct_utils as sct import os #path = '/Users/benjamindeleener/data/data_testing/C2-T2/' contrast = 't2' #path_output_seg = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/labels/' #path_output_im = '/Users/benjamindeleener/data/spinal_cord_segmentation_data/training/dat...
if not data_subjects: sct.printv('ERROR: No subject data were found in ' + folder_dataset + '. ' 'Please organize your data correctly or provide a correct dataset.', verbose=verbose, type='error') return data_subjects, subjects_dir data_subjects, subjects_name =...
if not subject_dir.startswith('.') and os.path.isdir(folder_dataset + subject_dir): data_subjects.append(folder_dataset + subject_dir + '/') subjects_dir.append(subject_dir)
conditional_block
DirectvsRNN.py
''' Copyleft Oct 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com ''' import pandas as pd import pylab as plt import matplotlib as mpl from matplotlib.cm import * import os,sys;home=os.path.expanduser('~') +'/' mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']...
plt.subplot(1,2,1) plt.plot(y_appr,x, color='red',linewidth=2, label='$\sigma(st/2-c)$') plt.plot(y,x, color='blue',linewidth=2,label='$x_t$') plt.xlim([-5,5]);plt.legend(loc='upper left') plt.ylabel('$x_t$') plt.xlabel('$st/2-c$') plt.grid() plt.subplot(1,2,2) print (y_appr-y) plt.plot(y,sig(y)-x, linewidth=2,label='E...
random_line_split
DirectvsRNN.py
''' Copyleft Oct 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com ''' import pandas as pd import pylab as plt import matplotlib as mpl from matplotlib.cm import * import os,sys;home=os.path.expanduser('~') +'/' mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']...
(z): return 1./(1+np.exp(-z)) fig=plt.figure(figsize=(30,10), dpi=100) fig.hold(True) y_appr=np.log(x)- np.log(1-x) y=np.log(x)- (1+s)*np.log(1-x) x.shape df=pd.DataFrame([x,y,y_appr],index=['x','y','z']).T plt.subplot(1,2,1) plt.plot(y_appr,x, color='red',linewidth=2, label='$\sigma(st/2-c)$') plt.plot(y,x, color='bl...
sig
identifier_name
DirectvsRNN.py
''' Copyleft Oct 24, 2015 Arya Iranmehr, PhD Student, Bafna's Lab, UC San Diego, Email: airanmehr@gmail.com ''' import pandas as pd import pylab as plt import matplotlib as mpl from matplotlib.cm import * import os,sys;home=os.path.expanduser('~') +'/' mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']...
fig=plt.figure(figsize=(30,10), dpi=100) fig.hold(True) y_appr=np.log(x)- np.log(1-x) y=np.log(x)- (1+s)*np.log(1-x) x.shape df=pd.DataFrame([x,y,y_appr],index=['x','y','z']).T plt.subplot(1,2,1) plt.plot(y_appr,x, color='red',linewidth=2, label='$\sigma(st/2-c)$') plt.plot(y,x, color='blue',linewidth=2,label='$x_t$'...
return 1./(1+np.exp(-z))
identifier_body
fractalbuilder.ts
import * as Utils from "./utils" import { ResponseData } from "./responsedata" import { GradData, Color } from "../gradient/graddata" import { Point } from './point' import { ColorComputer } from '../colorcomputer' export class FractalBuilder { private dataparts: Array<ResponseData> private data: Array<Uint32Array>...
let coords = Utils.getcoords(mevent, instance.canvas, instance.pixelratio, instance.center) if (instance.ready) { switch (e.type) { case 'mousewheel': if (wevent.deltaY > 0) instance.zoomout() else instance.zoomin(coords) break case 'DOMMouseScroll': if (wevent.detail > 0) insta...
random_line_split
fractalbuilder.ts
import * as Utils from "./utils" import { ResponseData } from "./responsedata" import { GradData, Color } from "../gradient/graddata" import { Point } from './point' import { ColorComputer } from '../colorcomputer' export class FractalBuilder { private dataparts: Array<ResponseData> private data: Array<Uint32Array>...
} }
{ let color = comp.getcolor(this.steps, i) this.redcolorchanel[i] = color.r this.greencolorchanel[i] = color.g this.bluecolorchanel[i] = color.b }
conditional_block
fractalbuilder.ts
import * as Utils from "./utils" import { ResponseData } from "./responsedata" import { GradData, Color } from "../gradient/graddata" import { Point } from './point' import { ColorComputer } from '../colorcomputer' export class FractalBuilder { private dataparts: Array<ResponseData> private data: Array<Uint32Array>...
() { let _this = this; _this.timer = (new Date()).getTime() _this.ready = false; let height = Math.floor(_this.canvas.height / _this.threadsnumber) let postdata = { type: _this.type, width: _this.canvas.width, height: height, steps: _this.steps, pixelratio: _this.pixelratio, x: _this.center...
generate
identifier_name
typeinfo.rs
use super::types; // this implements some kind of manual reflection pub trait TypeInfo { fn visit_fields<F>(cb: F) where F: Fn(&str /* name */, usize /* offset */, usize /* count */, types::GlTypeEnum);
macro_rules! impl_typeinfo { ($t:ty, $($field:ident),+) => ( impl $crate::typeinfo::TypeInfo for $t { fn visit_fields<F>(cb: F) where F: Fn(&str, usize, usize, ::types::GlTypeEnum) { use $crate::types::{GlType, ElemCount, GlTypeEnum}; ...
}
random_line_split
plotter.py
#! /usr/bin/env python import sys import os import re import glob import argparse from matplotlib import pyplot def main(args = sys.argv[1:]): """ Plot results from either Bitcoin Traffic Bulletin or this repository. """ opts = parse_args(args) generate_spike_plots(opts.datadir, opts.plotdir) ...
(plotdir, datasets): pyplot.figure() for rate, (times, _, cumulatives) in sorted(datasets.items()): pyplot.plot(times, cumulatives, label='{}'.format(rate)) pyplot.gca().set_xscale('log') plotpath = os.path.join(plotdir, 'load-spike-cumulatives.png') print('Writing plot: {!r}'.format(plot...
plot_spike_data
identifier_name
plotter.py
#! /usr/bin/env python import sys import os import re import glob import argparse from matplotlib import pyplot def main(args = sys.argv[1:]): """ Plot results from either Bitcoin Traffic Bulletin or this repository. """ opts = parse_args(args) generate_spike_plots(opts.datadir, opts.plotdir) ...
def parse_spike_data(datadir): fnamergx = re.compile(r'^.*/load-spike-(\d+\.\d+):(\d+\.\d+)-(\d+)-(\d+).cl-dat$') fixedparams = None datasets = {} for path in glob.glob('{}/load-spike-*.cl-dat'.format(datadir)): m = fnamergx.match(path) try: time, rate, blocks, sims = m....
datasets = parse_spike_data(datadir) plot_spike_data(plotdir, datasets)
identifier_body
plotter.py
#! /usr/bin/env python import sys import os import re import glob import argparse from matplotlib import pyplot def main(args = sys.argv[1:]): """ Plot results from either Bitcoin Traffic Bulletin or this repository. """ opts = parse_args(args) generate_spike_plots(opts.datadir, opts.plotdir) ...
else: if fixedparams != params: warnuser( 'Skipping plot {!r} which has params {!r}, expected {!r}.', path, params, fixedparams) continue datasets[rate] = (times, freqs, cumulatives) return datasets def plot_spi...
fixedparams = params
conditional_block
plotter.py
#! /usr/bin/env python import sys import os import re import glob import argparse from matplotlib import pyplot def main(args = sys.argv[1:]): """ Plot results from either Bitcoin Traffic Bulletin or this repository. """ opts = parse_args(args) generate_spike_plots(opts.datadir, opts.plotdir) ...
if __name__ == '__main__': main()
random_line_split
SimpleBinaryTree.py
# simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self):...
current_depth+=1 self.left.insert(newNode, max_depth, current_depth) else: if(self.right == None): self.right = BinaryTree(newNode) else: ''' ...
self.left = BinaryTree(newNode) else: if(current_depth < max_depth):
random_line_split
SimpleBinaryTree.py
# simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def
(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self): return self.right def setNodeValue(self,value): self.rootid = value def getNodeValue(self): return self.rootid...
__init__
identifier_name
SimpleBinaryTree.py
# simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self):...
''' def insert(item, tree): if (item < tree.entry): if (tree.left != None): insert(item, tree.left) else: tree.left = Tree(item) else: if (tree.right...
if(current_depth < max_depth): current_depth+=1 self.left.insert(newNode, max_depth, current_depth) else: if(self.right == None): self.right = BinaryTree(newNode) else:
conditional_block
SimpleBinaryTree.py
# simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self):...
# test tree def testTree(): myTree = BinaryTree("Maud") myTree.insertLeft("Bob") myTree.insertRight("Tony") myTree.insertRight("Steven") printTree(myTree) testTree()
if tree != None: printTree(tree.getLeftChild()) print(tree.getNodeValue()) printTree(tree.getRightChild())
identifier_body
Animexis.js
Entry.js. //If your implementation works and has been fully tested, send it to me with an //icon (png with transparency file, 16x16) for your mirror //at pl dot duhoux (at) gmail dot com. I will add it in the extension. //If you have problems implementing your mirror, send me a mail... i will be glad to help you... //C...
return null; }, //This method is called to fill the previous button's url in the manga site navigation bar //The select containing the mangas list next to the button is passed in argument previousChapterUrl : function(select, doc, curUrl) { //This function runs in the DOM of the current consulted page....
{ return $(select).children("option:selected").prev().val(); }
conditional_block
Animexis.js
mgEntry.js. //If your implementation works and has been fully tested, send it to me with an //icon (png with transparency file, 16x16) for your mirror //at pl dot duhoux (at) gmail dot com. I will add it in the extension. //If you have problems implementing your mirror, send me a mail... i will be glad to help you... ...
pages.forEach(function(page) { res.push(page.url); }); return res; }, //Remove the banners from the current page removeBanners : function(doc, curUrl) { //This function runs in the DOM of the current consulted page. }, //This method returns the place to write the full chapter in the document //...
//This function can return urls which are not the source of the //images. The src of the image is set by the getImageFromPageAndWrite() function. getListImages : function(doc, curUrl) { var res = []; eval($('body', doc).html().match(/var pages = .*\n/)[0]);
random_line_split
image-resizer.component.ts
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core'; import { ModalService } from '../../services'; @Component({ selector: 'app-image-resizer', templateUrl: './image-resizer.component.html', styleUrls: ['./image-resizer.component.scss'], }) export class ImageResizerComponent implements...
// Create the file reader const reader = new FileReader(); // If there is a file // Start reading this file this.readFile(file, reader, (result: any) => { // Create an img element and add the image file data to it const img = document.createElement('img'); img.src = result; ...
readFiles(file: any, callback: any) {
random_line_split
image-resizer.component.ts
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core'; import { ModalService } from '../../services'; @Component({ selector: 'app-image-resizer', templateUrl: './image-resizer.component.html', styleUrls: ['./image-resizer.component.scss'], }) export class ImageResizerComponent implements...
get imageSource(): string { return this.file_src || this.src; } ngOnInit() { } onSave() { this.save.next(this.file_src); this.file_src = null; } onRemove(input: HTMLInputElement) { if (this.file_src) { this.file_src = null; input.value = ''; return; } if (this....
{ }
identifier_body
image-resizer.component.ts
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core'; import { ModalService } from '../../services'; @Component({ selector: 'app-image-resizer', templateUrl: './image-resizer.component.html', styleUrls: ['./image-resizer.component.scss'], }) export class ImageResizerComponent implements...
else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } // create a canvas object const canvas = document.createElement('canvas'); // Set the canvas to the new calculated dimensions canvas.width = width; canvas.h...
{ if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } }
conditional_block
image-resizer.component.ts
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core'; import { ModalService } from '../../services'; @Component({ selector: 'app-image-resizer', templateUrl: './image-resizer.component.html', styleUrls: ['./image-resizer.component.scss'], }) export class ImageResizerComponent implements...
(file: any, callback: any) { // Create the file reader const reader = new FileReader(); // If there is a file // Start reading this file this.readFile(file, reader, (result: any) => { // Create an img element and add the image file data to it const img = document.createElement('img'); ...
readFiles
identifier_name
KickstartFetch.py
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the im...
def getFetchURL(self, channelLabel, ksLabel, ksFilePath): return self.baseURL + "/SAT/$RHN/" + channelLabel + "/getKickstartFile/" + ksLabel + "/" + ksFilePath; def fetchItem(self, itemInfo): authMap = self.login() fileName = itemInfo['fileName'] itemSize = itemInfo['size...
return self.rhnComm.login(refresh)
identifier_body