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
index.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (...
{ next }) { // Execute each child route until one of them return the result const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`; route.description = route.description || ''; return route; ...
ction(
identifier_name
index.js
* React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (pare...
/**
random_line_split
index.js
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (...
};
// Execute each child route until one of them return the result const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`; route.description = route.description || ''; return route; },
identifier_body
MessageBox.py
from Screen import Screen from Components.ActionMap import ActionMap from Components.Label import Label from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuList from enigma import eTimer class MessageBox(Screen): TYPE_YESNO = 0 TYPE_INFO = 1 ...
(self): self.move(self["list"].instance.moveUp) def down(self): self.move(self["list"].instance.moveDown) def left(self): self.move(self["list"].instance.pageUp) def right(self): self.move(self["list"].instance.pageDown) def move(self, direction): if self.close_on_any_key: self.close(True) self["...
up
identifier_name
MessageBox.py
from Screen import Screen from Components.ActionMap import ActionMap from Components.Label import Label from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuList from enigma import eTimer class MessageBox(Screen): TYPE_YESNO = 0 TYPE_INFO = 1 ...
self.setTitle(self.origTitle) self.timerRunning = False def timerTick(self): if self.execing: self.timeout -= 1 if self.origTitle is None: self.origTitle = self.instance.getTitle() self.setTitle(self.origTitle + " (" + str(self.timeout) + ")") if self.timeout == 0: self.timer.stop() se...
random_line_split
MessageBox.py
from Screen import Screen from Components.ActionMap import ActionMap from Components.Label import Label from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuList from enigma import eTimer class MessageBox(Screen): TYPE_YESNO = 0 TYPE_INFO = 1 ...
def initTimeout(self, timeout): self.timeout = timeout if timeout > 0: self.timer = eTimer() self.timer.callback.append(self.timerTick) self.onExecBegin.append(self.startTimer) self.origTitle = None if self.execing: self.timerTick() else: self.onShown.append(self.__onShown) self.time...
self.type = type Screen.__init__(self, session) if simple: self.skinName="MessageBoxSimple" self.msgBoxID = msgBoxID self["text"] = Label(text) self["Text"] = StaticText(text) self["selectedChoice"] = StaticText() self.text = text self.close_on_any_key = close_on_any_key self["ErrorPixmap"]...
identifier_body
MessageBox.py
from Screen import Screen from Components.ActionMap import ActionMap from Components.Label import Label from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuList from enigma import eTimer class MessageBox(Screen): TYPE_YESNO = 0 TYPE_INFO = 1 ...
self.stopTimer() def __repr__(self): return str(type(self)) + "(" + self.text + ")"
self["selectedChoice"].setText(self["list"].getCurrent()[0])
conditional_block
__init__.py
from bacnet import BACNetTransform from cwmp import CWMPTransform from dns import DNSTransform from ftp import FTPTransform from http import HTTPTransform from http import HTTPWWWTransform from https import HTTPSTransform from https import HTTPSGetTransform
from https import DHEExportTransform from https import ECDHETransform from https import TLSv10Transform from https import TLSv11Transform from https import TLSv12Transform from https import TLSv13Transform from https import SSLv3Transform from imap import IMAPStartTLSTransform from imap import IMAPSTransform from modb...
from https import HTTPSWWWTransform from https import HeartbleedTransform from https import RSAExportTransform from https import DHETransform
random_line_split
approve_order_mutation.test.ts
/* eslint-disable promise/always-return */ import { runQuery } from "schema/v1/test/utils" import { sampleOrder } from "test/fixtures/results/sample_order" import exchangeOrderJSON from "test/fixtures/exchange/buy_order.json" import { mockxchange } from "test/fixtures/exchange/mockxchange" import gql from "lib/gql" imp...
... on OrderWithMutationFailure { error { type code data } } } } } ` return runQuery(mutation, context).then((data) => { expect(data!.approveOrder.orderOrError.order).toEqual(sample...
... on OrderWithMutationSuccess { order { ${OrderSellerFields} } }
random_line_split
ciphersuite.rs
struct Ciphersuite { code: u16, kex_algo: ~str, sig_algo: ~str, cipher: ~str, cipher_keylen: u8, mac: ~str } impl Ciphersuite { static fn new(suite: u16, kex_algo: ~str, sig_algo: ~str, cipher: ~str, cipher_keylen: u8, mac: ~str) -> Ciphersuite { Ciphersuite { ...
out } } #[cfg(test)] mod tests { #[test] fn test() { let psk = Ciphersuite::from_code(0x008A); io::println(fmt!("%?", psk)); } }
_ => fail ~"Unknown mac" };
random_line_split
ciphersuite.rs
struct
{ code: u16, kex_algo: ~str, sig_algo: ~str, cipher: ~str, cipher_keylen: u8, mac: ~str } impl Ciphersuite { static fn new(suite: u16, kex_algo: ~str, sig_algo: ~str, cipher: ~str, cipher_keylen: u8, mac: ~str) -> Ciphersuite { Ciphersuite { code: s...
Ciphersuite
identifier_name
app.js
#!/bin/env node 'use strict';
Parser = require('./lib/parser'), ApiWrapper = require('./lib/api-wrapper'); var date = new Date(); date = date.toJSON().replace(/(-|:)/g, '.'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'silly'}); winston.add(winston.transports.File, { filename: path.jo...
var winston = require('winston'), path = require('path'), mcapi = require('mailchimp-api'),
random_line_split
course_home_messages.py
""" View logic for handling course messages. """ from __future__ import absolute_import from datetime import datetime from babel.dates import format_date, format_timedelta from django.contrib import auth from django.template.loader import render_to_string from django.utils.http import urlquote_plus from django.utils...
def _register_course_goal_message(request, course): """ Register a message to let a learner specify a course goal. """ course_goal_options = get_course_goal_options() goal_choices_html = Text(_( 'To start, set a course goal by selecting the option below that best describes ' u'you...
""" Register messages to be shown in the course home content page. """ allow_anonymous = allow_public_access(course, [COURSE_VISIBILITY_PUBLIC]) if user_access['is_anonymous'] and not allow_anonymous: sign_in_or_register_text = (_(u'{sign_in_link} or {register_link} and then enroll in this cour...
identifier_body
course_home_messages.py
""" View logic for handling course messages. """ from __future__ import absolute_import from datetime import datetime from babel.dates import format_date, format_timedelta from django.contrib import auth from django.template.loader import render_to_string from django.utils.http import urlquote_plus from django.utils...
elif not course.invitation_only: CourseHomeMessages.register_info_message( request, Text(_( u'{open_enroll_link}Enroll now{close_enroll_link} to access the full course.' )).format( open_enroll_link=HTML('<button...
CourseHomeMessages.register_info_message( request, Text(_('You must be enrolled in the course to see course content. ' 'Please contact your degree administrator or edX Support if you have questions.')), title=title )
conditional_block
course_home_messages.py
""" View logic for handling course messages. """ from __future__ import absolute_import from datetime import datetime from babel.dates import format_date, format_timedelta from django.contrib import auth from django.template.loader import render_to_string from django.utils.http import urlquote_plus from django.utils...
(self, request, course_id, user_access, **kwargs): """ Renders a course message fragment for the specified course. """ course_key = CourseKey.from_string(course_id) course = get_course_with_access(request.user, 'load', course_key) # Get time until the start date, if alre...
render_to_fragment
identifier_name
course_home_messages.py
""" View logic for handling course messages. """ from __future__ import absolute_import from datetime import datetime from babel.dates import format_date, format_timedelta from django.contrib import auth from django.template.loader import render_to_string from django.utils.http import urlquote_plus from django.utils...
# Register the course home messages to be loaded on the page _register_course_home_messages(request, course, user_access, course_start_data) # Register course date alerts for course_date_block in get_course_date_blocks(course, request.user): course_date_block.register_alert...
'days_until_start_string': days_until_start_string }
random_line_split
talk_time.py
# -*- coding: utf-8 -*- # # talk_time.py # # Copyright 2017 Cimbali <me@cimba.li> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License,...
(self): """ Forces to reset the default colors on the label. """ self.color_override.load_from_data(''.encode('ascii')) def update_time_color(self, remaining): """ Update the color of the time label based on how much time is remaining. Args: remaining (`int`): ...
default_color
identifier_name
talk_time.py
# -*- coding: utf-8 -*- # # talk_time.py # # Copyright 2017 Cimbali <me@cimba.li> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License,...
# You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """ :mod:`pympress.talk_time` -- Manages the clock of elapsed talk time -----------...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. #
random_line_split
talk_time.py
# -*- coding: utf-8 -*- # # talk_time.py # # Copyright 2017 Cimbali <me@cimba.li> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License,...
Update the timer and clock labels. Returns: `bool`: `True` (to prevent the timer from stopping) """ # Current time clock = time.strftime('%X') # '%H:%M:%S' elapsed = self.current_time() # Time elapsed since the beginning of the presentation if self....
identifier_body
talk_time.py
# -*- coding: utf-8 -*- # # talk_time.py # # Copyright 2017 Cimbali <me@cimba.li> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License,...
return True
.label_colorer.default_color()
conditional_block
mustache.d.ts
// Type definitions for Mustache 0.8.2 // Project: https://github.com/janl/mustache.js // Definitions by: Mark Ashley Bell <https://github.com/markashleybell/> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface MustacheScanner {
eos(): boolean; scan(re: RegExp): string; scanUntil(re: RegExp): string; } interface MustacheContext { view: any; parentContext: MustacheContext; push(view: any): MustacheContext; lookup(name: string): any; } interface MustacheWriter { (view: any): string; clear...
string: string; tail: string; pos: number;
random_line_split
network.rs
extern crate byteorder; use std::io::prelude::*; use std::io::{ Result, Error, ErrorKind, }; use std::net::{ TcpListener, TcpStream, SocketAddr, IpAddr, Ipv4Addr, }; use std::thread::{ Builder, JoinHandle, }; use std::sync::mpsc::{ channel, Sender, Receiver, }; use s...
match establish_connection( &mut stream ) { Ok( _ ) => { response[ 0 ] = RESPONSE_CODE_OK; if let Err( e ) = send_data( &mut stream, &response ) { error!( "{}", e ); error!( "Deni...
info!( "Connection request from {}", peer_addr ); let mut response : [u8; 3] = [0; 3]; // Establish a proper client connection
random_line_split
network.rs
extern crate byteorder; use std::io::prelude::*; use std::io::{ Result, Error, ErrorKind, }; use std::net::{ TcpListener, TcpStream, SocketAddr, IpAddr, Ipv4Addr, }; use std::thread::{ Builder, JoinHandle, }; use std::sync::mpsc::{ channel, Sender, Receiver, }; use s...
( &self ) -> u8 { self.data[ 0 ] } } impl Server { pub fn new() -> Server { let ( stream_sender, stream_receiver ) = channel::<TcpStream>(); let builder = Builder::new().name( String::from( "Server thread" ) ); let listener = TcpListener::bind( "0.0.0.0:9090" ).expect( "Couldn'...
get_type
identifier_name
network.rs
extern crate byteorder; use std::io::prelude::*; use std::io::{ Result, Error, ErrorKind, }; use std::net::{ TcpListener, TcpStream, SocketAddr, IpAddr, Ipv4Addr, }; use std::thread::{ Builder, JoinHandle, }; use std::sync::mpsc::{ channel, Sender, Receiver, }; use s...
if count != PROTOCOL_HEADER.len() { return Err( Error::new( ErrorKind::Other, "Invalid number of bytes received." ) ); } for i in 0..PROTOCOL_HEADER.len() { if header[ i ] != PROTOCOL_HEADER[ i ] { return Err( Error::new( ErrorKind::Other, "Invalid header received." ) ); ...
{ return Err( Error::new( ErrorKind::Other, "Connection closed." ) ); }
conditional_block
FonttblDestinations.ts
/* The MIT License (MIT) Copyright (c) 2015 Thomas Bluemel 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, merg...
} else { this.fontname += text; } } public apply(): void { if (this.index == null) { throw new RTFJSError("No font index provided"); } if (this.fontname == null) { throw new RTFJSError("No font name provided"); } this._...
this.fontname = text;
random_line_split
FonttblDestinations.ts
/* The MIT License (MIT) Copyright (c) 2015 Thomas Bluemel 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, merg...
(text: string): void { if (this.fontname == null) { this.fontname = text; } else { this.fontname += text; } } public apply(): void { if (this.index == null) { throw new RTFJSError("No font index provided"); } if (this.fontname ...
appendText
identifier_name
FonttblDestinations.ts
/* The MIT License (MIT) Copyright (c) 2015 Thomas Bluemel 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, merg...
else { this.fontname += text; } } public apply(): void { if (this.index == null) { throw new RTFJSError("No font index provided"); } if (this.fontname == null) { throw new RTFJSError("No font name provided"); } this._fonttbl.a...
{ this.fontname = text; }
conditional_block
middleware.py
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.shortcuts import redirect from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware(object): def __i...
if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_...
patch_vary_headers(response, ('Cookie',))
conditional_block
middleware.py
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.shortcuts import redirect from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware(object): def __i...
(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, sa...
process_request
identifier_name
middleware.py
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.shortcuts import redirect from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware(object): def __i...
def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the ...
engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore
identifier_body
middleware.py
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.shortcuts import redirect from django.utils.cache import patch_vary_headers from django.utils.http import cookie_date class SessionMiddleware(object): def __i...
httponly=settings.SESSION_COOKIE_HTTPONLY or None) return response
random_line_split
0023_update_choices.py
# Generated by Django 2.2.11 on 2020-04-15 13:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coredata', '0022_add_new_visit_data'), ] operations = [ migrations.AlterField( model_name='combinedoffering', name=...
model_name='courseoffering', name='instr_mode', field=models.CharField(choices=[('CO', 'Co-Op'), ('DE', 'Distance Education'), ('GI', 'Graduate Internship'), ('P', 'In Person'), ('PO', 'In Person - Off Campus'), ('PR', 'Practicum'), ('PF', 'In Person Field School')], db_index=True, d...
model_name='courseoffering', name='component', field=models.CharField(choices=[('LEC', 'Lecture'), ('LAB', 'Lab'), ('TUT', 'Tutorial'), ('SEM', 'Seminar'), ('SEC', 'Section'), ('PRA', 'Practicum'), ('IND', 'Individual Work'), ('INS', 'INS'), ('WKS', 'Workshop'), ('FLD', 'Field School...
random_line_split
0023_update_choices.py
# Generated by Django 2.2.11 on 2020-04-15 13:46 from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('coredata', '0022_add_new_visit_data'), ] operations = [ migrations.AlterField( model_name='combinedoffering', name='component', field=models.CharField(choices=[('LEC', 'Lecture'), ('LAB', 'Lab'), ('TUT', 'Tutori...
Migration
identifier_name
0023_update_choices.py
# Generated by Django 2.2.11 on 2020-04-15 13:46 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('coredata', '0022_add_new_visit_data'), ] operations = [ migrations.AlterField( model_name='combinedoffering', name='component', field=models.CharField(choices=[('LEC', 'Lecture'), ('LAB', 'Lab'), ('TUT', 'Tutorial'), ('SEM', 'Seminar'), ('S...
identifier_body
document_loader.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/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
self.blocking_loads.remove(idx.expect(&format!("unknown completed load {:?}", load))); } pub fn is_blocked(&self) -> bool { // TODO: Ensure that we report blocked if parsing is still ongoing. !self.blocking_loads.is_empty() } pub fn inhibit_events(&mut self) { self.even...
/// Mark an in-progress network request complete. pub fn finish_load(&mut self, load: &LoadType) { let idx = self.blocking_loads.iter().position(|unfinished| *unfinished == *load);
random_line_split
document_loader.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/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
(existing: &DocumentLoader) -> DocumentLoader { DocumentLoader::new_with_thread(existing.resource_thread.clone(), None, None) } /// We use an `Arc<ResourceThread>` here in order to avoid file descriptor exhaustion when there /// are lots of iframes. pub fn new_with_thread(resource_thread: Arc<R...
new
identifier_name
document_loader.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/. */ //! Tracking of pending loads in a document. //! https://html.spec.whatwg.org/multipage/#the-end use dom::binding...
/// We use an `Arc<ResourceThread>` here in order to avoid file descriptor exhaustion when there /// are lots of iframes. pub fn new_with_thread(resource_thread: Arc<ResourceThread>, pipeline: Option<PipelineId>, initial_load: Option<Url>) ...
{ DocumentLoader::new_with_thread(existing.resource_thread.clone(), None, None) }
identifier_body
recursion_limit.rs
// Copyright 2012 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 ...
// this via an attribute on the crate like `#![recursion_limit="22"]`. This pass // just peeks and looks for that attribute. use session::Session; use syntax::ast; use syntax::attr::AttrMetaMethods; use std::str::FromStr; pub fn update_recursion_limit(sess: &Session, krate: &ast::Crate) { for attr in krate.attrs....
// There are various parts of the compiler that must impose arbitrary limits // on how deeply they recurse to prevent stack overflow. Users can override
random_line_split
recursion_limit.rs
// Copyright 2012 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 ...
(sess: &Session, krate: &ast::Crate) { for attr in krate.attrs.iter() { if !attr.check_name("recursion_limit") { continue; } if let Some(s) = attr.value_str() { if let Some(n) = FromStr::from_str(s.get()) { sess.recursion_limit.set(n); ...
update_recursion_limit
identifier_name
recursion_limit.rs
// Copyright 2012 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 ...
{ for attr in krate.attrs.iter() { if !attr.check_name("recursion_limit") { continue; } if let Some(s) = attr.value_str() { if let Some(n) = FromStr::from_str(s.get()) { sess.recursion_limit.set(n); return; } } ...
identifier_body
recursion_limit.rs
// Copyright 2012 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 ...
} span_err!(sess, attr.span, E0296, "malformed recursion limit attribute, \ expected #![recursion_limit=\"N\"]"); } }
{ sess.recursion_limit.set(n); return; }
conditional_block
loggers.d.ts
import * as ts from "typescript"; export declare enum LogLevel { Verbose = 0, Info = 1, Warn = 2, Error = 3, Success = 4, } export declare class Logger { errorCount: number; hasErrors(): boolean; resetErrors(): void; write(text: string, ...args: string[]): void; writeln(text: str...
extends Logger { log(message: string, level?: LogLevel, newLine?: boolean): void; } export declare class CallbackLogger extends Logger { callback: Function; constructor(callback: Function); log(message: string, level?: LogLevel, newLine?: boolean): void; }
ConsoleLogger
identifier_name
loggers.d.ts
import * as ts from "typescript"; export declare enum LogLevel { Verbose = 0, Info = 1, Warn = 2, Error = 3, Success = 4, } export declare class Logger { errorCount: number; hasErrors(): boolean; resetErrors(): void; write(text: string, ...args: string[]): void; writeln(text: str...
log(message: string, level?: LogLevel, newLine?: boolean): void; }
random_line_split
Toptip.js
'use strict'; import React, {Component, PropTypes} from 'react'; import ReactNative, {View, Text} from 'react-native'; var Popover = require('../Popover'); var AutoHide = require('./AutoHide'); var ToptipAnimation = require('../Popover/PopoverAnimationVertical').create( {onStartShouldSetResponder: () => false} ); c...
} const styles = { layer: { right: 0, }, toptip: { alignSelf: 'stretch', }, text: { fontSize: 15, padding: 10, fontWeight: 'bold', textAlign: 'center', }, }; module.exports = Toptip;
{ const { text, duration, type, style, children, ...other, } = this.props; const {toptip, spacing} = this.context.uiTheme; const paddingTop = spacing.statusbarHeight; const backgroundColor = toptip.backgroundColors[type]; const color = toptip.colors[type]; let content = children; if...
identifier_body
Toptip.js
'use strict'; import React, {Component, PropTypes} from 'react'; import ReactNative, {View, Text} from 'react-native'; var Popover = require('../Popover'); var AutoHide = require('./AutoHide'); var ToptipAnimation = require('../Popover/PopoverAnimationVertical').create( {onStartShouldSetResponder: () => false} ); cl...
<Popover layerStyle={styles.layer} {...other} useLayerForClickAway={true} animation={ToptipAnimation} style={[styles.toptip, {backgroundColor, paddingTop}, style]}> {content} </Popover> ); } } const styles = { layer: { right: 0, }, toptip: { alignSelf: 'stretch', }, text...
return (
random_line_split
Toptip.js
'use strict'; import React, {Component, PropTypes} from 'react'; import ReactNative, {View, Text} from 'react-native'; var Popover = require('../Popover'); var AutoHide = require('./AutoHide'); var ToptipAnimation = require('../Popover/PopoverAnimationVertical').create( {onStartShouldSetResponder: () => false} ); c...
() { const { text, duration, type, style, children, ...other, } = this.props; const {toptip, spacing} = this.context.uiTheme; const paddingTop = spacing.statusbarHeight; const backgroundColor = toptip.backgroundColors[type]; const color = toptip.colors[type]; let content = children; ...
render
identifier_name
Toptip.js
'use strict'; import React, {Component, PropTypes} from 'react'; import ReactNative, {View, Text} from 'react-native'; var Popover = require('../Popover'); var AutoHide = require('./AutoHide'); var ToptipAnimation = require('../Popover/PopoverAnimationVertical').create( {onStartShouldSetResponder: () => false} ); c...
return ( <Popover layerStyle={styles.layer} {...other} useLayerForClickAway={true} animation={ToptipAnimation} style={[styles.toptip, {backgroundColor, paddingTop}, style]}> {content} </Popover> ); } } const styles = { layer: { right: 0, }, toptip: { alignSelf: 'stretch', ...
{ content = ( <Text style={[styles.text, {color}]}> {text} </Text> ); }
conditional_block
response.py
# urllib3/response.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import gzip import logging import zlib from io import BytesIO from .exceptions import HTTPEr...
else: return self._fp.read(amt) try: if decode_content and decoder: data = decoder(data) except IOError: raise HTTPError("Received response with content-encoding: %s, but " "failed t...
data = self._fp.read()
conditional_block
response.py
# urllib3/response.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import gzip import logging import zlib from io import BytesIO from .exceptions import HTTPEr...
else: return self._fp.read(amt) try: if decode_content and decoder: data = decoder(data) except IOError: raise HTTPError("Received response with content-encoding: %s, but " "failed to...
try: if amt is None: # cStringIO doesn't like amt=None data = self._fp.read()
random_line_split
response.py
# urllib3/response.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import gzip import logging import zlib from io import BytesIO from .exceptions import HTTPEr...
def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: r...
""" Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in [301, 302, 303, 307]: ...
identifier_body
response.py
# urllib3/response.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import gzip import logging import zlib from io import BytesIO from .exceptions import HTTPEr...
(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default)
getheaders
identifier_name
accessibilityHelp.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): void { this._widget.show(); } public hide(): void { this._widget.hide(); } } function getSelectionLabel(selections: Selection[] | null, charactersSelected: number): string { if (!selections || selections.length === 0) { return AccessibilityHelpNLS.noSelection; } if (selections.length === 1) { if (...
show
identifier_name
accessibilityHelp.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const AccessibilityHelpCommand = EditorCommand.bindToContribution<AccessibilityHelpController>(AccessibilityHelpController.get); registerEditorCommand( new AccessibilityHelpCommand({ id: 'closeAccessibilityHelp', precondition: CONTEXT_ACCESSIBILITY_WIDGET_VISIBLE, handler: x => x.hide(), kbOpts: { weight:...
registerEditorAction(ShowAccessibilityHelpAction);
random_line_split
accessibilityHelp.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (selections.length === 1) { if (charactersSelected) { return strings.format(AccessibilityHelpNLS.singleSelectionRange, selections[0].positionLineNumber, selections[0].positionColumn, charactersSelected); } return strings.format(AccessibilityHelpNLS.singleSelection, selections[0].positionLineNumber, sele...
{ return AccessibilityHelpNLS.noSelection; }
conditional_block
accessibilityHelp.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public getPosition(): IOverlayWidgetPosition { return { preference: null }; } public show(): void { if (this._isVisible) { return; } this._isVisible = true; this._isVisibleKey.set(true); this._layout(); this._domNode.setDisplay('block'); this._domNode.setAttribute('aria-hidden', 'false'); ...
{ return this._domNode.domNode; }
identifier_body
predict.py
import numpy as np import pandas as pd import tensorflow as tf import scipy.misc from keras.utils import plot_model from keras.preprocessing.image import ImageDataGenerator from keras.models import Model, Sequential from keras.layers import Input, Dropout, Activation, LSTM, Conv2D, Conv2DTranspose, Dense, TimeDistribu...
def merge(yo, error, p, q): ae, be, ce = np.split(error, 3, axis=4) ag, bg, cg = np.split(yo, 3, axis=4) a = combine(ae, ag, p, q) b = combine(be, bg, p, q) c = combine(ce, cg, p, q) return np.concatenate((a, b, c), axis=4) def wrt(yo, error, name, p, q, c): out = merge(...
p, m = np.split(e, 2, axis=4) return np.sign(g + np.sign(p-p1) - np.sign(m-q1))
identifier_body
predict.py
import numpy as np import pandas as pd import tensorflow as tf import scipy.misc from keras.utils import plot_model from keras.preprocessing.image import ImageDataGenerator from keras.models import Model, Sequential from keras.layers import Input, Dropout, Activation, LSTM, Conv2D, Conv2DTranspose, Dense, TimeDistribu...
(m, dim, acti, bn, res, do=0.2): n = TimeDistributed(Conv2D(dim, 6, padding='same'))(m) n = TimeDistributed(LeakyReLU())(n) n = BatchNormalization()(n) if bn else n n = TimeDistributed(Dropout(do))(n) if do else n n = TimeDistributed(Conv2D(dim, 6, padding='same'))(n) n = TimeDistributed(LeakyRe...
conv_block
identifier_name
predict.py
import numpy as np import pandas as pd import tensorflow as tf import scipy.misc from keras.utils import plot_model from keras.preprocessing.image import ImageDataGenerator from keras.models import Model, Sequential from keras.layers import Input, Dropout, Activation, LSTM, Conv2D, Conv2DTranspose, Dense, TimeDistribu...
t_mask = (t_mask * 2) - 1 n_mask = (n_mask * 2) - 1 return np.concatenate((t_mask, n_mask), axis=4) def extractGT(seq): gt, data = np.split(batch_sequence, [output_dimension], axis=4) gta, gtb, gtc = np.split(gt, 3, axis=4) z1, z2, z3, z4, cta, ctb, ctc = np.split(data, input_dimen...
n_mask = np.clip(ct - gt, 0, 1)
random_line_split
predict.py
import numpy as np import pandas as pd import tensorflow as tf import scipy.misc from keras.utils import plot_model from keras.preprocessing.image import ImageDataGenerator from keras.models import Model, Sequential from keras.layers import Input, Dropout, Activation, LSTM, Conv2D, Conv2DTranspose, Dense, TimeDistribu...
n = Concatenate()([n, m]) m = conv_block(n, dim, acti, bn, res) else: m = conv_block(m, dim, acti, bn, res, do) l = TimeDistributed(Flatten())(m) #l = LSTM(4 * 4 * 128, stateful=True, return_sequences=True)(l) l = LSTM(2048, stateful=True, retur...
m = TimeDistributed(Conv2DTranspose(dim, 4, strides=2, padding='same'))(m) m = TimeDistributed(LeakyReLU())(m)
conditional_block
springbatchPlugin.ts
/// <reference path="./helpers.ts"/>
export var pluginName = 'SpringBatch'; export var _module = angular.module(pluginName, ['bootstrap', 'ngResource', 'hawtioCore', 'hawtio-ui']); _module.config(["$routeProvider", ($routeProvider) => { $routeProvider .when('/springbatch/servers', {templateUrl: SpringBatch.templatePath + ...
module SpringBatch { export var templatePath = 'app/springbatch/html/';
random_line_split
test_mistipy.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_mistipy ---------------------------------- Tests for `mistipy` module. """ import pytest # from contextlib import contextmanager from click.testing import CliRunner # from mistipy import mistipy from mistipy import cli @pytest.fixture def response():
def test_content(response): """Sample pytest test function with the pytest fixture as an argument. """ # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string def test_command_line_interface(): runner = CliRunner() result = runner.invoke(cli.main) ...
"""Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage')
identifier_body
test_mistipy.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_mistipy ---------------------------------- Tests for `mistipy` module. """ import pytest # from contextlib import contextmanager from click.testing import CliRunner
@pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixtur...
# from mistipy import mistipy from mistipy import cli
random_line_split
test_mistipy.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_mistipy ---------------------------------- Tests for `mistipy` module. """ import pytest # from contextlib import contextmanager from click.testing import CliRunner # from mistipy import mistipy from mistipy import cli @pytest.fixture def
(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument. """ ...
response
identifier_name
utils.py
from copy import copy import json from cnxepub.utils import squash_xml_to_text from cnxml.parse import parse_metadata as parse_cnxml_metadata from cnxtransforms import cnxml_abstract_to_html from lxml import etree __all__ = ( 'convert_to_model_compat_metadata', 'scan_for_id_mapping', 'scan_for_uuid_mappi...
""" mapping = {} for filepath in start_dir.glob('**/index.cnxml'): with filepath.open('rb') as fb: xml = etree.parse(fb) md = convert_to_model_compat_metadata(parse_cnxml_metadata(xml)) id = id_from_metadata(md) id = id.split('@')[0] mapping[id] = filepath...
:param start_dir: a directory to start the scan from :type start_dir: :class:`pathlib.Path` :return: mapping of content ids to the content filepath :rtype: {str: pathlib.Path, ...}
random_line_split
utils.py
from copy import copy import json from cnxepub.utils import squash_xml_to_text from cnxml.parse import parse_metadata as parse_cnxml_metadata from cnxtransforms import cnxml_abstract_to_html from lxml import etree __all__ = ( 'convert_to_model_compat_metadata', 'scan_for_id_mapping', 'scan_for_uuid_mappi...
def build_id_to_uuid_mapping(id_to_path_map, uuid_to_path_map): """Build a mapping of ID to UUID values based upon matching paths :param id_to_path_map: A mapping of IDs (m12345) to filepaths :type id_to_path_map: {str: pathlib.Path, ...} :param uuid_to_path_map: A mapping of UUIDs to filepaths ...
"""Collect a mapping of content UUIDs to filepaths relative to the given directory (as ``start_dir``). This is similar to ``scan_for_id_mapping``, but instead of using the ID value found in CNXML as the key, we want the same mapping keyed by the UUID in the corresponding metadata.json file if it's avai...
identifier_body
utils.py
from copy import copy import json from cnxepub.utils import squash_xml_to_text from cnxml.parse import parse_metadata as parse_cnxml_metadata from cnxtransforms import cnxml_abstract_to_html from lxml import etree __all__ = ( 'convert_to_model_compat_metadata', 'scan_for_id_mapping', 'scan_for_uuid_mappi...
return mapping def scan_for_uuid_mapping(start_dir): """Collect a mapping of content UUIDs to filepaths relative to the given directory (as ``start_dir``). This is similar to ``scan_for_id_mapping``, but instead of using the ID value found in CNXML as the key, we want the same mapping keyed by t...
with filepath.open('rb') as fb: xml = etree.parse(fb) md = convert_to_model_compat_metadata(parse_cnxml_metadata(xml)) id = id_from_metadata(md) id = id.split('@')[0] mapping[id] = filepath
conditional_block
utils.py
from copy import copy import json from cnxepub.utils import squash_xml_to_text from cnxml.parse import parse_metadata as parse_cnxml_metadata from cnxtransforms import cnxml_abstract_to_html from lxml import etree __all__ = ( 'convert_to_model_compat_metadata', 'scan_for_id_mapping', 'scan_for_uuid_mappi...
(start_dir): """Collect a mapping of content UUIDs to filepaths relative to the given directory (as ``start_dir``). This is similar to ``scan_for_id_mapping``, but instead of using the ID value found in CNXML as the key, we want the same mapping keyed by the UUID in the corresponding metadata.json ...
scan_for_uuid_mapping
identifier_name
d3viz.py
"""Dynamic visualization of Theano graphs. Author: Christof Angermueller <cangermueller@gmail.com> """ import os import shutil import re from six import iteritems from theano.d3viz.formatting import PyDotFormatter __path__ = os.path.dirname(os.path.realpath(__file__)) def replace_patterns(x, replace): """Repl...
`key`, `value` pairs where key is a regular expression and `value` a string by which `key` is replaced """ for from_, to in iteritems(replace): x = x.replace(str(from_), str(to)) return x def escape_quotes(s): """Escape quotes in string. Parameters ---------- s : s...
s : str String on which function is applied replace : dict
random_line_split
d3viz.py
"""Dynamic visualization of Theano graphs. Author: Christof Angermueller <cangermueller@gmail.com> """ import os import shutil import re from six import iteritems from theano.d3viz.formatting import PyDotFormatter __path__ = os.path.dirname(os.path.realpath(__file__)) def replace_patterns(x, replace): """Repl...
def d3viz(fct, outfile, copy_deps=True, *args, **kwargs): """Create HTML file with dynamic visualizing of a Theano function graph. In the HTML file, the whole graph or single nodes can be moved by drag and drop. Zooming is possible via the mouse wheel. Detailed information about nodes and edges are ...
"""Escape quotes in string. Parameters ---------- s : str String on which function is applied """ s = re.sub(r'''(['"])''', r'\\\1', s) return s
identifier_body
d3viz.py
"""Dynamic visualization of Theano graphs. Author: Christof Angermueller <cangermueller@gmail.com> """ import os import shutil import re from six import iteritems from theano.d3viz.formatting import PyDotFormatter __path__ = os.path.dirname(os.path.realpath(__file__)) def replace_patterns(x, replace): """Repl...
else: dst_deps = src_deps # Replace patterns in template replace = { '%% JS_DIR %%': os.path.join(dst_deps, 'js'), '%% CSS_DIR %%': os.path.join(dst_deps, 'css'), '%% DOT_GRAPH %%': dot_graph, } html = replace_patterns(template, replace) # Write HTML file w...
dst_deps = 'd3viz' for d in ['js', 'css']: dep = os.path.join(outdir, dst_deps, d) if not os.path.exists(dep): shutil.copytree(os.path.join(src_deps, d), dep)
conditional_block
d3viz.py
"""Dynamic visualization of Theano graphs. Author: Christof Angermueller <cangermueller@gmail.com> """ import os import shutil import re from six import iteritems from theano.d3viz.formatting import PyDotFormatter __path__ = os.path.dirname(os.path.realpath(__file__)) def
(x, replace): """Replace `replace` in string `x`. Parameters ---------- s : str String on which function is applied replace : dict `key`, `value` pairs where key is a regular expression and `value` a string by which `key` is replaced """ for from_, to in iteritems(re...
replace_patterns
identifier_name
async.py
# Copyright 2011 Nicholas Bray # # 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...
return func def async_limited(count): def limited_func(func): semaphore = threading.BoundedSemaphore(count) # closure with func and semaphore def thread_wrap(*args, **kargs): result = func(*args, **kargs) semaphore.release() return result # closure with thread_wrap and semaphore @functools.wrap...
else:
random_line_split
async.py
# Copyright 2011 Nicholas Bray # # 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...
else: return func def async_limited(count): def limited_func(func): semaphore = threading.BoundedSemaphore(count) # closure with func and semaphore def thread_wrap(*args, **kargs): result = func(*args, **kargs) semaphore.release() return result # closure with thread_wrap and semaphore @functo...
return async_wrapper
conditional_block
async.py
# Copyright 2011 Nicholas Bray # # 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...
(*args, **kargs): t = threading.Thread(target=func, args=args, kwargs=kargs) t.start() return t if enabled: return async_wrapper else: return func def async_limited(count): def limited_func(func): semaphore = threading.BoundedSemaphore(count) # closure with func and semaphore def thread_wrap(*args...
async_wrapper
identifier_name
async.py
# Copyright 2011 Nicholas Bray # # 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...
if enabled: return async_wrapper else: return func def async_limited(count): def limited_func(func): semaphore = threading.BoundedSemaphore(count) # closure with func and semaphore def thread_wrap(*args, **kargs): result = func(*args, **kargs) semaphore.release() return result # closure wit...
t = threading.Thread(target=func, args=args, kwargs=kargs) t.start() return t
identifier_body
0004_auto_20160905_0938.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def port_models(apps, schema_editor): Proposal = apps.get_model('core', 'Proposal') Notice = apps.get_model('core', 'Notice') n = Notice() n.title = "Edital" n.description = "Edital info" ...
dependencies = [ ('core', '0003_proposaldate'), ] operations = [ migrations.CreateModel( name='Notice', fields=[ ('id', models.AutoField(serialize=False, primary_key=True)), ('title', models.CharField(max_length=60)), ('des...
identifier_body
0004_auto_20160905_0938.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def port_models(apps, schema_editor): Proposal = apps.get_model('core', 'Proposal') Notice = apps.get_model('core', 'Notice') n = Notice() n.title = "Edital" n.description = "Edital info" ...
(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('core', '0003_proposaldate'), ] operations = [ migrations.CreateModel( name='Notice', fields=[ ('id', models.AutoField(serialize=False, primary_key=True)), ...
reverse_port_models
identifier_name
0004_auto_20160905_0938.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def port_models(apps, schema_editor): Proposal = apps.get_model('core', 'Proposal') Notice = apps.get_model('core', 'Notice') n = Notice() n.title = "Edital" n.description = "Edital info" ...
def reverse_port_models(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('core', '0003_proposaldate'), ] operations = [ migrations.CreateModel( name='Notice', fields=[ ('id', models.AutoField(serialize=False...
p.notice = n p.save()
conditional_block
0004_auto_20160905_0938.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def port_models(apps, schema_editor): Proposal = apps.get_model('core', 'Proposal')
n.save() for p in Proposal.objects.all(): p.notice = n p.save() def reverse_port_models(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('core', '0003_proposaldate'), ] operations = [ migrations.CreateModel( nam...
Notice = apps.get_model('core', 'Notice') n = Notice() n.title = "Edital" n.description = "Edital info"
random_line_split
bookmarks.rs
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * 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, ...
self.error(&err.to_string()); } self.components.mg.emit(DeleteCompletionItem); }, _ => (), } } pub fn set_tags(&self, tags: Option<String>) { // Do not edit tags when the user press Escape. if le...
if let Err(err) = self.model.bookmark_manager.delete(url) {
random_line_split
bookmarks.rs
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * 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, ...
(&self) { let mut command = self.model.command_text.split_whitespace(); match command.next() { Some("open") | Some("win-open") | Some("private-win-open") => if let Some(url) = command.next() { // Do not show message when deleting a bookmark in completion. ...
delete_selected_bookmark
identifier_name
bookmarks.rs
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * 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, ...
, _ => (), } } pub fn set_tags(&self, tags: Option<String>) { // Do not edit tags when the user press Escape. if let Some(tags) = tags { let tags: Vec<_> = tags.split(',') .map(|tag| tag.trim().to_lowercase()) .filter(|tag| !tag.is...
{ // Do not show message when deleting a bookmark in completion. if let Err(err) = self.model.bookmark_manager.delete(url) { self.error(&err.to_string()); } self.components.mg.emit(DeleteCompletionItem); ...
conditional_block
bookmarks.rs
/* * Copyright (c) 2016-2018 Boucher, Antoni <bouanto@zoho.com> * * 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, ...
/// Delete the bookmark selected in completion. pub fn delete_selected_bookmark(&self) { let mut command = self.model.command_text.split_whitespace(); match command.next() { Some("open") | Some("win-open") | Some("private-win-open") => if let Some(url) = command.nex...
{ if let Some(url) = self.widgets.webview.get_uri() { match self.model.bookmark_manager.delete(&url) { Ok(true) => self.components.mg.emit(Info(format!("Deleted bookmark: {}", url))), Ok(false) => self.info_page_not_in_bookmarks(), Err(err) => self.err...
identifier_body
dart.js
var which = require('which'); var spawnSync = require('child_process').spawnSync; module.exports.detect = function(gulp) { var DART_SDK = false; try { which.sync('dart'); if (process.platform === 'win32') { DART_SDK = { ANALYZER: 'dartanalyzer.bat', DARTDOCGEN: 'dartdoc.bat', ...
else { return gulpTaskFn(name, function() { console.log('Dart SDK is not available. Skipping task: ' + name); }); } }; } return DART_SDK; } module.exports.logVersion = function(dartSdk) { console.log('DART SDK:') ; console.log('- dart: ' + spawnSync(dartSdk.VM, ['--version'...
{ return gulpTaskFn(name, deps, fn); }
conditional_block
dart.js
var which = require('which'); var spawnSync = require('child_process').spawnSync; module.exports.detect = function(gulp) { var DART_SDK = false; try { which.sync('dart'); if (process.platform === 'win32') { DART_SDK = { ANALYZER: 'dartanalyzer.bat', DARTDOCGEN: 'dartdoc.bat', ...
module.exports.logVersion = function(dartSdk) { console.log('DART SDK:') ; console.log('- dart: ' + spawnSync(dartSdk.VM, ['--version']).stderr.toString().replace(/\n/g, '')); console.log('- pub: ' + spawnSync(dartSdk.PUB, ['--version']).stdout.toString().replace(/\n/g, '')); }
return DART_SDK; }
random_line_split
code_lexer.rs
pub struct CodeLexer<'a> { pub source: &'a str, } impl<'a> CodeLexer<'a> { pub fn new(source: &'a str) -> CodeLexer<'a> { CodeLexer { source: source } } pub fn is_keyword(&self, identifier: &str) -> bool { match identifier { "if" | "for" | "model" | "while" | "match" | "use...
pub fn end_of_code_block(&self) -> Option<usize> { self.end_of_block('{', '}') } pub fn end_of_code_statement(&self) -> Option<usize> { self.next_instance_of(';') } pub fn block_delimiters(&self) -> (Option<usize>, Option<usize>) { (self.next_instance_of('{'), self.end_of...
{ self.source.chars().position(|c| c == search_char) }
identifier_body
code_lexer.rs
pub struct CodeLexer<'a> { pub source: &'a str, } impl<'a> CodeLexer<'a> { pub fn new(source: &'a str) -> CodeLexer<'a> { CodeLexer { source: source } } pub fn is_keyword(&self, identifier: &str) -> bool { match identifier { "if" | "for" | "model" | "while" | "match" | "use...
(&self) -> Option<usize> { self.end_of_block('{', '}') } pub fn end_of_code_statement(&self) -> Option<usize> { self.next_instance_of(';') } pub fn block_delimiters(&self) -> (Option<usize>, Option<usize>) { (self.next_instance_of('{'), self.end_of_block('{', '}')) } }
end_of_code_block
identifier_name
code_lexer.rs
pub struct CodeLexer<'a> { pub source: &'a str, } impl<'a> CodeLexer<'a> { pub fn new(source: &'a str) -> CodeLexer<'a> { CodeLexer { source: source } } pub fn is_keyword(&self, identifier: &str) -> bool { match identifier { "if" | "for" | "model" | "while" | "match" | "use...
'A'...'Z' | 'a'...'z' | '_' => true, '0'...'9' if index > 0 => true, _ => false, }) .map(|(_, c)| c) .collect::<String>() } pub fn end_of_block(&self, start_char: char, end_char: char) -> Option<usize> { let mut scope =...
.chars() .enumerate() .take_while(|&(index, c)| match c {
random_line_split
gulpfile.js
var gulp = require('gulp'), jshint = require('gulp-jshint'), mocha = require('gulp-mocha'), cover = require('gulp-coverage'), jscs = require('gulp-jscs'); gulp.task('default', ['jscs', 'lint', 'test'], function () { }); gulp.task('lint', function () { return gulp.src(['./lib/*.js', './test/*.js'])...
});
gulp.task('jscs', function () { return gulp.src(['./lib/*.js', './test/*.js']) .pipe(jscs());
random_line_split
vc_line_chart.js
(function ( $ ) { /** * Generate line/bar charts * * Legend must be generated manually. If color is array (gradient), then legend won't show it. */ $.fn.vcLineChart = function () { this.each( function () { var data, gradient, chart, i, j, $this = $( this ), ctx = $...
! window.vc_iframe && vc_line_charts(); } ); }( jQuery ));
$( selector ).vcLineChart(); }; } $( document ).ready( function () {
random_line_split
vc_line_chart.js
(function ( $ ) { /** * Generate line/bar charts * * Legend must be generated manually. If color is array (gradient), then legend won't show it. */ $.fn.vcLineChart = function () { this.each( function () { var data, gradient, chart, i, j, $this = $( this ), ctx = $...
$this.data( 'vcChartId', chart.id ); // We can later access chart to call methods on it $this.data( 'chart', chart ); } ); return this; }; /** * Allows users to rewrite function inside theme. */ if ( 'function' !== typeof( window.vc_line_charts ) ) { window.vc_line_charts = functio...
{ chart = new Chart( ctx ).Line( data, options ); }
conditional_block
pyunit_NOFEATURE_prostateGLM.py
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd
import statsmodels.api as sm def prostate(ip,port): # Log.info("Importing prostate.csv data...\n") h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate("smalldata/logreg/prostate.csv")).as_matrix() sm_data_response = sm_dat...
random_line_split
pyunit_NOFEATURE_prostateGLM.py
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import statsmodels.api as sm def prostate(ip,port): # Log.info("Importing prostate.csv data...\n") h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate...
h2o.run_test(sys.argv, prostate)
conditional_block
pyunit_NOFEATURE_prostateGLM.py
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import statsmodels.api as sm def prostate(ip,port): # Log.info("Importing prostate.csv data...\n")
if __name__ == "__main__": h2o.run_test(sys.argv, prostate)
h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate("smalldata/logreg/prostate.csv")).as_matrix() sm_data_response = sm_data[:,1] sm_data_features = sm_data[:,2:] #Log.info(cat("B)H2O GLM (binomial) with parameters:\nX:", myX, "\n...
identifier_body
pyunit_NOFEATURE_prostateGLM.py
import sys sys.path.insert(1, "../../../") import h2o import pandas as pd import statsmodels.api as sm def
(ip,port): # Log.info("Importing prostate.csv data...\n") h2o_data = h2o.upload_file(path=h2o.locate("smalldata/logreg/prostate.csv")) #prostate.summary() sm_data = pd.read_csv(h2o.locate("smalldata/logreg/prostate.csv")).as_matrix() sm_data_response = sm_data[:,1] sm_data_features = sm_data[:,2:] ...
prostate
identifier_name
talker_handler.rs
use crate::talker::Talker; pub struct TalkerHandlerBase { pub category: String, pub model: String, pub label: String, } impl TalkerHandlerBase { pub fn new(category: &str, model: &str, label: &str) -> Self { Self { category: category.to_string(), model: model.to_string(...
pub fn model<'a>(&'a self) -> &'a String { &self.model } pub fn label<'a>(&'a self) -> &'a String { &self.label } } pub trait TalkerHandler { fn base<'a>(&'a self) -> &'a TalkerHandlerBase; fn category<'a>(&'a self) -> &'a String { &self.base().category } fn mo...
{ &self.category }
identifier_body
talker_handler.rs
use crate::talker::Talker; pub struct TalkerHandlerBase { pub category: String, pub model: String, pub label: String, } impl TalkerHandlerBase { pub fn new(category: &str, model: &str, label: &str) -> Self { Self { category: category.to_string(), model: model.to_string(...
&self.base().label } fn make(&self) -> Result<Box<dyn Talker>, failure::Error>; }
&self.base().model } fn label<'a>(&'a self) -> &'a String {
random_line_split
talker_handler.rs
use crate::talker::Talker; pub struct TalkerHandlerBase { pub category: String, pub model: String, pub label: String, } impl TalkerHandlerBase { pub fn new(category: &str, model: &str, label: &str) -> Self { Self { category: category.to_string(), model: model.to_string(...
<'a>(&'a self) -> &'a String { &self.base().label } fn make(&self) -> Result<Box<dyn Talker>, failure::Error>; }
label
identifier_name
build_and_test.py
#!/usr/bin/env python3 # Copyright 2014, 2016 Open Source Robotics Foundation, Inc. # # 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 # # Unl...
if __name__ == '__main__': sys.exit(main())
parser = argparse.ArgumentParser( description='Invoke the build tool on a workspace while enabling and ' 'running the tests') parser.add_argument( '--rosdistro-name', required=True, help='The name of the ROS distro to identify the setup file to be ' '...
identifier_body
build_and_test.py
#!/usr/bin/env python3 # Copyright 2014, 2016 Open Source Robotics Foundation, Inc. # # 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 # # Unl...
sys.exit(main())
conditional_block