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
credential.rs
use std::collections::HashMap; use ursa::cl::{ CredentialSignature, RevocationRegistry, SignatureCorrectnessProof, Witness }; use indy_api_types::validation::Validatable; use super::credential_definition::CredentialDefinitionId; use super::revocation_registry_definition::RevocationRegistryId; use sup...
self.values.validate()?; if self.rev_reg_id.is_some() && (self.witness.is_none() || self.rev_reg.is_none()) { return Err(String::from("Credential validation failed: `witness` and `rev_reg` must be passed for revocable Credential")); } if self.values.0.is_empty() { ...
self.cred_def_id.validate()?;
random_line_split
hof.rs
#![feature(iter_arith)] fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2, ... to infinity for n in 0.. { // Square the number let n_s...
// Functional approach let sum_of_squared_odd_numbers: u32 = (0..).map(|n| n * n) // All natural numbers squared .take_while(|&n| n < upper) // Below upper limit .filter(|n| is_odd(*n)) // That are odd .sum(); // Sum them pri...
} println!("imperative style: {}", acc);
random_line_split
hof.rs
#![feature(iter_arith)] fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2, ... to infinity for n in 0.. { // Square the number let n_s...
} println!("imperative style: {}", acc); // Functional approach let sum_of_squared_odd_numbers: u32 = (0..).map(|n| n * n) // All natural numbers squared .take_while(|&n| n < upper) // Below upper limit .filter(|n| is_odd(*n)) // That are odd ...
{ // Accumulate value, if it's odd acc += n_squared; }
conditional_block
hof.rs
#![feature(iter_arith)] fn
() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2, ... to infinity for n in 0.. { // Square the number let n_squared = n * n; if n_sq...
main
identifier_name
hof.rs
#![feature(iter_arith)] fn main() { println!("Find the sum of all the squared odd numbers under 1000"); let upper = 1000; // Imperative approach // Declare accumulator variable let mut acc = 0; // Iterate: 0, 1, 2, ... to infinity for n in 0.. { // Square the number let n_s...
{ n % 2 == 1 }
identifier_body
slice_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. /// SliceStack holds a non-guarded stack allocated elsewhere and provided as a mutable slice. /// /// Any slice used in a SliceStack mus...
#[inline(always)] fn limit(&self) -> *mut u8 { self.0.as_ptr() as *mut u8 } }
{ // The slice cannot wrap around the address space, so the conversion from usize // to isize will not wrap either. let len: isize = self.0.len() as isize; unsafe { self.limit().offset(len) } }
identifier_body
slice_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. /// SliceStack holds a non-guarded stack allocated elsewhere and provided as a mutable slice. /// /// Any slice used in a SliceStack mus...
(&self) -> *mut u8 { self.0.as_ptr() as *mut u8 } }
limit
identifier_name
slice_stack.rs
// This file is part of libfringe, a low-level green threading library. // Copyright (c) whitequark <whitequark@whitequark.org> // See the LICENSE file included in this distribution. /// SliceStack holds a non-guarded stack allocated elsewhere and provided as a mutable slice. /// /// Any slice used in a SliceStack mus...
#[inline(always)] fn base(&self) -> *mut u8 { // The slice cannot wrap around the address space, so the conversion from usize // to isize will not wrap either. let len: isize = self.0.len() as isize; unsafe { self.limit().offset(len) } } #[inline(always)] fn limit(&s...
#[derive(Debug)] pub struct SliceStack<'a>(pub &'a mut [u8]); impl<'a> ::stack::Stack for SliceStack<'a> {
random_line_split
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn main() { env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("A...
; let server = coinched::server::http::Server::new(port); server.run(); }
{ 3000 }
conditional_block
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn
() { env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("Alexandre Bury <alexandre.bury@gmail.com>") .about("A coinche server") .arg(Arg::with_name("PORT") ...
main
identifier_name
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn main() { env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("A...
.short("p") .long("port") .takes_value(true)) .get_matches(); let port = if let Some(port) = matches.value_of("PORT") { match u16::from_str(port) { Ok(port) => port, Er...
.about("A coinche server") .arg(Arg::with_name("PORT") .help("Port to listen to (defaults to 3000)")
random_line_split
coinched.rs
extern crate coinched; extern crate clap; extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use clap::{Arg, App}; fn main()
} } } else { 3000 }; let server = coinched::server::http::Server::new(port); server.run(); }
{ env_logger::init().unwrap(); let matches = App::new("coinched") .version(env!("CARGO_PKG_VERSION")) .author("Alexandre Bury <alexandre.bury@gmail.com>") .about("A coinche server") .arg(Arg::with_name("PORT") ...
identifier_body
entry.rs
use consts::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Entry { pub cell: u8, pub num: u8, } impl Entry { #[inline] pub fn cell(self) -> usize { self.cell as usize } #[inline] pub fn row(self) -> u8 { self.cell as u8 / 9 } #[inline] pub fn col(self) -> u8 { self.cell as u8 % 9 } ...
#[inline] pub fn row_constraint(self) -> usize { self.row() as usize * 9 + self.num_offset() } #[inline] pub fn col_constraint(self) -> usize { self.col() as usize * 9 + self.num_offset() + COL_OFFSET } #[inline] pub fn field_constraint(self) -> usize { self.field() as usize * 9 + self.num_offset() + FIELD_...
{ self.num() as usize - 1 }
identifier_body
entry.rs
use consts::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Entry { pub cell: u8, pub num: u8, } impl Entry { #[inline] pub fn cell(self) -> usize { self.cell as usize } #[inline] pub fn row(self) -> u8 { self.cell as u8 / 9 } #[inline] pub fn col(self) -> u8 { self.cell as u8 % 9 } ...
0...80 => self.row_constraint(), 81...161 => self.col_constraint(), 162...242 => self.field_constraint(), 243...323 => self.cell_constraint(), _ => unreachable!(), } } }
#[inline] pub fn constrains(self, constraint_nr: usize) -> bool { constraint_nr == match constraint_nr {
random_line_split
entry.rs
use consts::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Entry { pub cell: u8, pub num: u8, } impl Entry { #[inline] pub fn
(self) -> usize { self.cell as usize } #[inline] pub fn row(self) -> u8 { self.cell as u8 / 9 } #[inline] pub fn col(self) -> u8 { self.cell as u8 % 9 } #[inline] pub fn field(self) -> u8 { self.row() / 3 * 3 + self.col() / 3 } #[inline] pub fn num(self) -> u8 { self.num } #[inline] pub fn conflicts_with(self, o...
cell
identifier_name
time.py
"""Offer time listening automation rules.""" from datetime import datetime import logging import voluptuous as vol from homeassistant.const import CONF_AT, CONF_PLATFORM from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import ( asyn...
hass, time_automation_listener, trigger_dt ) elif has_time: # Else if it has time, then track time change. remove = async_track_time_change( hass, time_automation_listener, ...
remove = async_track_point_in_time(
random_line_split
time.py
"""Offer time listening automation rules.""" from datetime import datetime import logging import voluptuous as vol from homeassistant.const import CONF_AT, CONF_PLATFORM from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import ( asyn...
hour = minute = second = 0 if has_date: # If input_datetime has date, then track point in time. trigger_dt = dt_util.DEFAULT_TIME_ZONE.localize( datetime(year, month, day, hour, minute, second) ) # Only set ...
remove = entities.get(entity_id) if remove: remove() removes.remove(remove) remove = None # Check state of entity. If valid, set up a listener. if new_state: has_date = new_state.attributes["has_date"] if has_date: year...
identifier_body
time.py
"""Offer time listening automation rules.""" from datetime import datetime import logging import voluptuous as vol from homeassistant.const import CONF_AT, CONF_PLATFORM from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import ( asyn...
(entity_id, old_state=None, new_state=None): # If a listener was already set up for entity, remove it. remove = entities.get(entity_id) if remove: remove() removes.remove(remove) remove = None # Check state of entity. If valid, set up a listener. ...
update_entity_trigger
identifier_name
time.py
"""Offer time listening automation rules.""" from datetime import datetime import logging import voluptuous as vol from homeassistant.const import CONF_AT, CONF_PLATFORM from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import ( asyn...
else: # If no time then use midnight. hour = minute = second = 0 if has_date: # If input_datetime has date, then track point in time. trigger_dt = dt_util.DEFAULT_TIME_ZONE.localize( datetime(year, month, day, ...
hour = new_state.attributes["hour"] minute = new_state.attributes["minute"] second = new_state.attributes["second"]
conditional_block
adv3.rs
#![allow(warnings)] // Goal #1: Eliminate the borrow check error in the `remove` method. pub struct Map<K: Eq, V> { elements: Vec<(K, V)>, } impl<K: Eq, V> Map<K, V> { pub fn new() -> Self { Map { elements: vec![] } } pub fn
(&mut self, key: K, value: V) { self.elements.push((key, value)); } pub fn get(&self, key: &K) -> Option<&V> { self.elements.iter().rev().find(|pair| pair.0 == *key).map(|pair| &pair.1) } pub fn remove(&mut self, key: &K) { let mut i : Option<usize> = None; for (index, pair...
insert
identifier_name
adv3.rs
#![allow(warnings)] // Goal #1: Eliminate the borrow check error in the `remove` method. pub struct Map<K: Eq, V> { elements: Vec<(K, V)>, } impl<K: Eq, V> Map<K, V> { pub fn new() -> Self { Map { elements: vec![] } } pub fn insert(&mut self, key: K, value: V) { self.elements.push((k...
, } } }
{}
conditional_block
adv3.rs
#![allow(warnings)] // Goal #1: Eliminate the borrow check error in the `remove` method. pub struct Map<K: Eq, V> { elements: Vec<(K, V)>, } impl<K: Eq, V> Map<K, V> {
pub fn new() -> Self { Map { elements: vec![] } } pub fn insert(&mut self, key: K, value: V) { self.elements.push((key, value)); } pub fn get(&self, key: &K) -> Option<&V> { self.elements.iter().rev().find(|pair| pair.0 == *key).map(|pair| &pair.1) } pub fn remove(...
random_line_split
fisher.py
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.utilities import blockCombine from scipy import mat, dot, outer from scipy.linalg import inv, cholesky def calcFisherInformation(sigma, invSigma=None, factorSigma=None):
def calcInvFisher(sigma, invSigma=None, factorSigma=None): """ Efficiently compute the exact inverse of the FIM of a Gaussian. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = cholesky(sigma) ...
""" Compute the exact Fisher Information Matrix of a Gaussian distribution, given its covariance matrix. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = cholesky(sigma) dim = sigma.shape[0] fim ...
identifier_body
fisher.py
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.utilities import blockCombine from scipy import mat, dot, outer from scipy.linalg import inv, cholesky def
(sigma, invSigma=None, factorSigma=None): """ Compute the exact Fisher Information Matrix of a Gaussian distribution, given its covariance matrix. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = chol...
calcFisherInformation
identifier_name
fisher.py
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.utilities import blockCombine from scipy import mat, dot, outer from scipy.linalg import inv, cholesky def calcFisherInformation(sigma, invSigma=None, factorSigma=None): """ Compute the exact Fisher Information Matrix of a Gaussian distribution, ...
return fim def calcInvFisher(sigma, invSigma=None, factorSigma=None): """ Efficiently compute the exact inverse of the FIM of a Gaussian. Returns a list of the diagonal blocks. """ if invSigma == None: invSigma = inv(sigma) if factorSigma == None: factorSigma = cho...
D = invSigma[k:, k:].copy() D[0, 0] += factorSigma[k, k] ** -2 fim.append(D)
conditional_block
fisher.py
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.utilities import blockCombine from scipy import mat, dot, outer from scipy.linalg import inv, cholesky def calcFisherInformation(sigma, invSigma=None, factorSigma=None): """ Compute the exact Fisher Information Matrix of a Gaussian distribution, ...
for k in range(dim): D = invSigma[k:, k:].copy() D[0, 0] += factorSigma[k, k] ** -2 fim.append(D) return fim def calcInvFisher(sigma, invSigma=None, factorSigma=None): """ Efficiently compute the exact inverse of the FIM of a Gaussian. Returns a list of the diago...
random_line_split
auth.guard.ts
import { Injectable } from "@angular/core"; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router"; import { AuthService } from "./auth.service"; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private auth: AuthService) ...
return true; } isAuthenticated(): boolean { return !!this.auth.getAccessTokenId(); } }
canActivate(): boolean { if (!this.isAuthenticated()) { this.router.navigate(['login']); return false; }
random_line_split
auth.guard.ts
import { Injectable } from "@angular/core"; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router"; import { AuthService } from "./auth.service"; @Injectable() export class AuthGuard implements CanActivate {
(private router: Router, private auth: AuthService) {} /* canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) { let path: string = next.url[0] ? next.url[0].path : ""; if (((path === "login") || (path === "register")) && this.isAuthenticated()) { this.router.navigate(["/"]); ...
constructor
identifier_name
auth.guard.ts
import { Injectable } from "@angular/core"; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router"; import { AuthService } from "./auth.service"; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private auth: AuthService) ...
return true; } isAuthenticated(): boolean { return !!this.auth.getAccessTokenId(); } }
{ this.router.navigate(['login']); return false; }
conditional_block
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""Dynamic resource editor for X Toolkit applications.""" homepage = "http://cgit.freedesktop.org/xorg/app/editres" url = "https://www.x.org/archive/individual/app/editres-1.0.6.tar.gz" version('1.0.6', '310c504347ca499874593ac96e935353') depends_on('libxaw') depends_on('libx11') depends...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(AutotoolsPackage): """Dynamic resource editor for X Toolkit applications.""" homepage = "http://cgit.freedesktop.org/xorg/app/editres" url = "https://www.x.org/archive/individual/app/editres-1.0.6.tar.gz" version('1.0.6', '310c504347ca499874593ac96e935353') depends_on('libxaw') depends_...
Editres
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""Dynamic resource editor for X Toolkit applications.""" homepage = "http://cgit.freedesktop.org/xorg/app/editres" url = "https://www.x.org/archive/individual/app/editres-1.0.6.tar.gz" version('1.0.6', '310c504347ca499874593ac96e935353') depends_on('libxaw') depends_on('libx11') dep...
class Editres(AutotoolsPackage):
random_line_split
countdown.ts
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import Timer = NodeJS.Timer; @Component({ selector: 'count-down', template: `<h1>{{displayString}}</h1><ng-content></ng-content>` }) export class CountDown implements OnInit { _to: Timer; @Input() units: any; @Input() end:...
(): void { if (typeof this.units === 'string') { this.units = this.units.toLowerCase().split('|'); } this.givenDate = new Date(this.end); if (!this.text) { this.text = { 'Weeks': 'Weeks', 'Days': 'Days', 'Hours': 'Hours', 'Minutes': 'Minutes', 'Seco...
ngOnInit
identifier_name
countdown.ts
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import Timer = NodeJS.Timer; @Component({ selector: 'count-down', template: `<h1>{{displayString}}</h1><ng-content></ng-content>` }) export class CountDown implements OnInit { _to: Timer; @Input() units: any; @Input() end:...
this._to = setInterval(() => this._displayString(), this.units['milliseconds'] ? 1 : 1000); } _displayString() { const now: any = new Date(), lastUnit = this.units[this.units.length - 1], unitsLeft = [], unitConstantMillis = { 'weeks': 6048e5, 'days': 864e5, '...
{ this.text = { 'Weeks': 'Weeks', 'Days': 'Days', 'Hours': 'Hours', 'Minutes': 'Minutes', 'Seconds': 'Seconds', 'MilliSeconds': 'Milliseconds' }; }
conditional_block
countdown.ts
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import Timer = NodeJS.Timer; @Component({ selector: 'count-down', template: `<h1>{{displayString}}</h1><ng-content></ng-content>` }) export class CountDown implements OnInit { _to: Timer; @Input() units: any; @Input() end:...
if (!unitConstantMillis[unit]) { // $interval.cancel(countDownInterval); throw new Error('Cannot repeat unit: ' + unit); } if (!unitConstantMillis.hasOwnProperty(unit)) { throw new Error('Unit: ' + unit + ' is not supported. Please use following units: weeks, days, hours, minu...
random_line_split
countdown.ts
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core'; import Timer = NodeJS.Timer; @Component({ selector: 'count-down', template: `<h1>{{displayString}}</h1><ng-content></ng-content>` }) export class CountDown implements OnInit { _to: Timer; @Input() units: any; @Input() end:...
} this.units.forEach((unit: string) => { if (!unitConstantMillis[unit]) { // $interval.cancel(countDownInterval); throw new Error('Cannot repeat unit: ' + unit); } if (!unitConstantMillis.hasOwnProperty(unit)) { throw new Error('Unit: ' + unit + ' is not supported. P...
{ const now: any = new Date(), lastUnit = this.units[this.units.length - 1], unitsLeft = [], unitConstantMillis = { 'weeks': 6048e5, 'days': 864e5, 'hours': 36e5, 'minutes': 6e4, 'seconds': 1e3, 'milliseconds': 1 }; let msLeft: any = this...
identifier_body
fault.rs
use std::panic::catch_unwind; use std::error::Error; use std::fmt; use std::io::{Write, stderr, Error as IoError, ErrorKind}; pub fn catch_fault() { let result = catch_unwind(|| { panic!("holy crap!"); }); println!("\n{:?}\n", result); } pub fn get_something() -> Result<(), String> { Err("hol...
let _ = writeln!(stderr(), "error: {}", err); while let Some(cause) = err.cause() { let _ = writeln!(stderr(), "caused by: {}", cause); err = cause; } } pub fn demo_print_std_err() { #[derive(Debug)] struct SuperErrorSideKick; impl fmt::Display for SuperErrorSideKick { f...
pub fn print_error(mut err: &Error) {
random_line_split
fault.rs
use std::panic::catch_unwind; use std::error::Error; use std::fmt; use std::io::{Write, stderr, Error as IoError, ErrorKind}; pub fn catch_fault() { let result = catch_unwind(|| { panic!("holy crap!"); }); println!("\n{:?}\n", result); } pub fn get_something() -> Result<(), String> { Err("hol...
} #[derive(Debug)] struct SuperError; impl fmt::Display for SuperError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SuperError is here!") } } impl Error for SuperError { fn description(&self) -> &str { "I'm the superhero of ...
{ "I'm SuperError side kick" }
identifier_body
fault.rs
use std::panic::catch_unwind; use std::error::Error; use std::fmt; use std::io::{Write, stderr, Error as IoError, ErrorKind}; pub fn catch_fault() { let result = catch_unwind(|| { panic!("holy crap!"); }); println!("\n{:?}\n", result); } pub fn get_something() -> Result<(), String> { Err("hol...
(&self) -> &str { "I'm the superhero of errors" } fn cause(&self) -> Option<&Error> { Some(&SuperErrorSideKick{}) } } let mut err = SuperError{}; println!("{:?}", err.cause()); print_error(&err); } pub fn err_propagation() -> Result<(), IoError> { Er...
description
identifier_name
extcolorbufferhalffloat.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use canvas_traits::webgl::WebGLVersion; use crat...
impl EXTColorBufferHalfFloat { fn new_inherited() -> EXTColorBufferHalfFloat { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for EXTColorBufferHalfFloat { type Extension = EXTColorBufferHalfFloat; fn new(ctx: &WebGLRenderingContext) -> DomRoot<EXTColorBuffe...
}
random_line_split
extcolorbufferhalffloat.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions}; use canvas_traits::webgl::WebGLVersion; use crat...
{ reflector_: Reflector, } impl EXTColorBufferHalfFloat { fn new_inherited() -> EXTColorBufferHalfFloat { Self { reflector_: Reflector::new(), } } } impl WebGLExtension for EXTColorBufferHalfFloat { type Extension = EXTColorBufferHalfFloat; fn new(ctx: &WebGLRenderingC...
EXTColorBufferHalfFloat
identifier_name
mars-stroke-h.js
import Icon from '../components/Icon.vue' Icon.register({ 'mars-stroke-h': { width: 480, height: 512, paths: [ { d: 'M476.2 247.5c4.7 4.7 4.7 12.3 0.1 17l-55.9 55.9c-7.6 7.5-20.5 2.2-20.5-8.5v-23.9h-23.9v20c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-20h-27.6c-5.8 25.6-18.7 49.9-38.6 69.8-5...
})
] }
random_line_split
index.js
/** * marked-tex-renderer * A plug-in style renderer to produce TeX output for marked * https://github.com/sampathsris/marked-tex-renderer */ /*jshint node: true */ 'use strict'; var NEWLINE = '\r\n'; function Renderer()
Renderer.prototype.failOnUnsupported = function() { if (!this.options.hasOwnProperty('failOnUnsupported')) { return true; } return this.options.failOnUnsupported; }; Renderer.prototype.code = function (code, lang, escaped) { return [ '\\begin{verbatim}', code, '\\end{verbatim}' ].join(N...
{ }
identifier_body
index.js
/** * marked-tex-renderer * A plug-in style renderer to produce TeX output for marked * https://github.com/sampathsris/marked-tex-renderer */ /*jshint node: true */ 'use strict'; var NEWLINE = '\r\n'; function Renderer() { } Renderer.prototype.failOnUnsupported = function() { if (!this.optio...
(html) { return html.replace(/&([#\w]+);/g, function(_, n) { n = n.toLowerCase(); if (n === 'colon') return ':'; if (n === 'amp') return '&'; if (n.charAt(0) === '#') { var charCode = 0; if (n.charAt(1) === 'x') { charCode = parseInt(n.substring(2), 16); } else { charCode = ...
htmlUnescape
identifier_name
index.js
/** * marked-tex-renderer * A plug-in style renderer to produce TeX output for marked * https://github.com/sampathsris/marked-tex-renderer */ /*jshint node: true */ 'use strict'; var NEWLINE = '\r\n'; function Renderer() { } Renderer.prototype.failOnUnsupported = function() { if (!this.optio...
}; Renderer.prototype.hr = function () { return '\\hrulefill' + NEWLINE; }; Renderer.prototype.list = function (body, ordered) { if (ordered) { return [ NEWLINE, '\\begin{enumerate}', body, '\\end{enumerate}', NEWLINE ].join(NEWLINE); } else { return [ NEWLINE, '\\begin...
return NEWLINE + command + '{' + text + '}' + NEWLINE;
random_line_split
index.js
/** * marked-tex-renderer * A plug-in style renderer to produce TeX output for marked * https://github.com/sampathsris/marked-tex-renderer */ /*jshint node: true */ 'use strict'; var NEWLINE = '\r\n'; function Renderer() { } Renderer.prototype.failOnUnsupported = function() { if (!this.optio...
}; Renderer.prototype.image = function (href, title, text) { if (this.options.imageRenderer) { return this.options.imageRenderer(href, title, text); } else if (this.failOnUnsupported()) { throw new Error( 'Client should provide a function to render images. ' + 'Use options.imageRenderer = functio...
{ // omit hyperlink and just return the text. return text; }
conditional_block
common.rs
use std::ffi::CString; use std::os::raw::c_char; #[macro_export] macro_rules! take_until_and_consume ( ( $i:expr, $needle:expr ) => ( { let input: &[u8] = $i; let (rem, res) = ::nom::take_until!(input, $needle)?; let (rem, _) = ::nom::take!(rem, $needle.len())?; Ok((rem, res)) } ); ...
drop(CString::from_raw(s)); }
{ return; }
conditional_block
common.rs
use std::ffi::CString; use std::os::raw::c_char; #[macro_export] macro_rules! take_until_and_consume ( ( $i:expr, $needle:expr ) => ( { let input: &[u8] = $i; let (rem, res) = ::nom::take_until!(input, $needle)?; let (rem, _) = ::nom::take!(rem, $needle.len())?; Ok((rem, res)) } ); ...
(s: String) -> *mut c_char { CString::new(s) .map(|c_str| c_str.into_raw()) .unwrap_or(std::ptr::null_mut()) } /// Free a CString allocated by Rust (for ex. using `rust_string_to_c`) /// /// # Safety /// /// s must be allocated by rust, using `CString::new` #[no_mangle] pub unsafe extern "C" fn rs_...
rust_string_to_c
identifier_name
common.rs
use std::ffi::CString; use std::os::raw::c_char; #[macro_export] macro_rules! take_until_and_consume ( ( $i:expr, $needle:expr ) => ( { let input: &[u8] = $i; let (rem, res) = ::nom::take_until!(input, $needle)?; let (rem, _) = ::nom::take!(rem, $needle.len())?; Ok((rem, res)) } ); ...
/// /// This function will consume the provided data and use the underlying bytes to construct a new /// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this /// function; the provided data should *not* contain any 0 bytes in it. /// /// Returns a valid pointer, or NULL pub fn...
/// Convert a String to C-compatible string
random_line_split
common.rs
use std::ffi::CString; use std::os::raw::c_char; #[macro_export] macro_rules! take_until_and_consume ( ( $i:expr, $needle:expr ) => ( { let input: &[u8] = $i; let (rem, res) = ::nom::take_until!(input, $needle)?; let (rem, _) = ::nom::take!(rem, $needle.len())?; Ok((rem, res)) } ); ...
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`) /// /// # Safety /// /// s must be allocated by rust, using `CString::new` #[no_mangle] pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) { if s.is_null() { return; } drop(CString::from_raw(s)); }
{ CString::new(s) .map(|c_str| c_str.into_raw()) .unwrap_or(std::ptr::null_mut()) }
identifier_body
test_misc.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
from unittest import mock import pytest from ..misc import pass_dummy_scans, check_valid_fs_license @pytest.mark.parametrize( "algo_dummy_scans,dummy_scans,expected_out", [(2, 1, 1), (2, None, 2), (2, 0, 0)] ) def test_pass_dummy_scans(algo_dummy_scans, dummy_scans, expected_out): """Check dummy scans passin...
import shutil
random_line_split
test_misc.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
@pytest.mark.skipif(shutil.which('mri_convert') is None, reason="FreeSurfer not installed") def test_fs_license_check3(monkeypatch): with monkeypatch.context() as m: m.delenv("FS_LICENSE", raising=False) m.delenv("FREESURFER_HOME", raising=False) assert check_valid_fs_license() is False
"""Execute the canary itself.""" assert check_valid_fs_license() is True
identifier_body
test_misc.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
(algo_dummy_scans, dummy_scans, expected_out): """Check dummy scans passing.""" skip_vols = pass_dummy_scans(algo_dummy_scans, dummy_scans) assert skip_vols == expected_out @pytest.mark.parametrize( "stdout,rc,valid", [ (b"Successful command", 0, True), (b"", 0, True), (b"...
test_pass_dummy_scans
identifier_name
https.rs
extern crate rustls; extern crate webpki_roots; use std::net::SocketAddr; use crate::name_server::RuntimeProvider; use crate::tls::CLIENT_CONFIG; use proto::xfer::{DnsExchange, DnsExchangeConnect}; use proto::TokioTime; use trust_dns_https::{ HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien...
}
{ https_test(ResolverConfig::cloudflare_https()) }
identifier_body
https.rs
extern crate rustls; extern crate webpki_roots; use std::net::SocketAddr; use crate::name_server::RuntimeProvider; use crate::tls::CLIENT_CONFIG; use proto::xfer::{DnsExchange, DnsExchangeConnect}; use proto::TokioTime; use trust_dns_https::{ HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien...
() { https_test(ResolverConfig::cloudflare_https()) } }
test_cloudflare_https
identifier_name
https.rs
extern crate rustls; extern crate webpki_roots; use std::net::SocketAddr; use crate::name_server::RuntimeProvider; use crate::tls::CLIENT_CONFIG; use proto::xfer::{DnsExchange, DnsExchangeConnect}; use proto::TokioTime; use trust_dns_https::{ HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien...
let resolver = TokioAsyncResolver::new(config, ResolverOpts::default(), io_loop.handle().clone()) .expect("failed to create resolver"); let response = io_loop .block_on(resolver.lookup_ip("www.example.com.")) .expect("failed to run lookup"); ...
random_line_split
https.rs
extern crate rustls; extern crate webpki_roots; use std::net::SocketAddr; use crate::name_server::RuntimeProvider; use crate::tls::CLIENT_CONFIG; use proto::xfer::{DnsExchange, DnsExchangeConnect}; use proto::TokioTime; use trust_dns_https::{ HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien...
} // check if there is another connection created let response = io_loop .block_on(resolver.lookup_ip("www.example.com.")) .expect("failed to run lookup"); assert_eq!(response.iter().count(), 1); for address in response.iter() { if address.i...
{ assert_eq!( address, IpAddr::V6(Ipv6Addr::new( 0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946, )) ); }
conditional_block
busy.js
angular.module('mnBusy',[]) .factory('busyTrackerFactory',['$timeout','$q', function($timeout,$q) { return function() { var tracker = {}; tracker.delayPromise = null; tracker.durationPromise = null; tracker.processingPromise = null; tracker.busyPromise = null; tracker.reset = ...
} return config; } return { restrict: 'A', scope: true, transclude: true, templateUrl: function(tElement,tAttrs){ config = buildConfig(tAttrs); return config.templateUrl; }, link: function(scope,element,attrs) { // expose the tracker,con...
{ angular.extend(config,$injector.get(busyConfigValueName)); }
conditional_block
busy.js
angular.module('mnBusy',[]) .factory('busyTrackerFactory',['$timeout','$q', function($timeout,$q) { return function() { var tracker = {}; tracker.delayPromise = null; tracker.durationPromise = null; tracker.processingPromise = null; tracker.busyPromise = null; tracker.reset = ...
}; tracker.isBusy = function() { return tracker.delayPromise === null && tracker.busyPromise !== null; }; tracker.isActive = function() { return tracker.delayPromise !== null || tracker.busyPromise !== null; }; return tracker; }; } ]) .di...
{ tracker.processingPromise = null; if ( tracker.delayPromise !== null) { // processing finioshed before delay is over => cancel delay and go on $timeout.cancel(tracker.delayPromise); } }
identifier_body
busy.js
angular.module('mnBusy',[]) .factory('busyTrackerFactory',['$timeout','$q', function($timeout,$q) { return function() { var tracker = {}; tracker.delayPromise = null;
tracker.processingPromise = null; tracker.busyPromise = null; tracker.reset = function(options) { // prepare tracked promises var promises = []; angular.forEach(options.promises,function(promise) { // skip invalid values if (!promise || typeof promise.then ...
tracker.durationPromise = null;
random_line_split
busy.js
angular.module('mnBusy',[]) .factory('busyTrackerFactory',['$timeout','$q', function($timeout,$q) { return function() { var tracker = {}; tracker.delayPromise = null; tracker.durationPromise = null; tracker.processingPromise = null; tracker.busyPromise = null; tracker.reset = ...
(attrs){ // start with empty config var config = {}; // add global defaults var busyDefaultsName = 'busyDefaults'; if ($injector.has(busyDefaultsName)){ angular.extend(config,$injector.get(busyDefaultsName)); } // add instance configs var busyConfigAttr = attrs...
buildConfig
identifier_name
test_lastpass.py
# (c)2016 Andrew Zenk <azenk@umn.edu> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
def test_lastpass_build_args_logout(self): lp = MockLPass() self.assertEqual(['logout', '--color=never'], lp._build_args("logout")) def test_lastpass_logged_in_true(self): lp = MockLPass() self.assertTrue(lp.logged_in) def test_lastpass_logged_in_false(self): lp =...
lp = MockLPass(path='/dev/null') self.assertEqual('/dev/null', lp.cli_path)
identifier_body
test_lastpass.py
# (c)2016 Andrew Zenk <azenk@umn.edu> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
elif stdin and stdin.lower() == 'y\n': return mock_exit(output='Log out: complete.', error=logged_in_error, rc=0) else: return mock_exit(error='Error: aborted response', rc=1) if args.subparser_name == 'show': if self._mock_logged_out: ...
return mock_exit(output='Log out: aborted.', error=logged_in_error, rc=1)
conditional_block
test_lastpass.py
# (c)2016 Andrew Zenk <azenk@umn.edu> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
(self, args, stdin=None, expected_rc=0): # Mock behavior of lpass executable base_options = ArgumentParser(add_help=False) base_options.add_argument('--color', default="auto", choices=['auto', 'always', 'never']) p = ArgumentParser() sp = p.add_subparsers(help='command', dest='s...
_run
identifier_name
test_lastpass.py
# (c)2016 Andrew Zenk <azenk@umn.edu> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ...
@patch('ansible.plugins.lookup.lastpass.LPass', LoggedOutMockLPass) def test_lastpass_plugin_logged_out(self): lookup_plugin = LookupModule() entry = MOCK_ENTRIES[0] entry_id = entry.get('id') with self.assertRaises(AnsibleError): lookup_plugin.run([entry_id], field...
for k, v in six.iteritems(entry): self.assertEqual(v.strip(), lookup_plugin.run([entry_id], field=k)[0])
random_line_split
wsgi.py
""" WSGI config for ahaha project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` se...
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ahaha.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_...
framework. """
random_line_split
PaymentMethodConfirmation.js
import PaddedView from '@ui/PaddedView'; import { Title, Row, TinyButton, TinyButtonText } from '../styles'; const enhance = compose( withRouter, mapProps(props => ({ onPressEdit() { props.history.push('address'); }, })), ); const PaymentMethodConfirmation = enhance(({ onPressEdit }) => ( <Back...
import React from 'react'; import { compose, mapProps } from 'recompose'; import { withRouter } from '@ui/NativeWebRouter'; import BackgroundView from '@ui/BackgroundView'; import SavedPaymentReviewForm from '@ui/forms/SavedPaymentReviewForm';
random_line_split
PaymentMethodConfirmation.js
import React from 'react'; import { compose, mapProps } from 'recompose'; import { withRouter } from '@ui/NativeWebRouter'; import BackgroundView from '@ui/BackgroundView'; import SavedPaymentReviewForm from '@ui/forms/SavedPaymentReviewForm'; import PaddedView from '@ui/PaddedView'; import { Title, Row, TinyButton, Ti...
() { props.history.push('address'); }, })), ); const PaymentMethodConfirmation = enhance(({ onPressEdit }) => ( <BackgroundView> <PaddedView> <Row> <Title>Review</Title> <TinyButton onPress={onPressEdit}> <TinyButtonText>Edit</TinyButtonText> </TinyButton> ...
onPressEdit
identifier_name
PaymentMethodConfirmation.js
import React from 'react'; import { compose, mapProps } from 'recompose'; import { withRouter } from '@ui/NativeWebRouter'; import BackgroundView from '@ui/BackgroundView'; import SavedPaymentReviewForm from '@ui/forms/SavedPaymentReviewForm'; import PaddedView from '@ui/PaddedView'; import { Title, Row, TinyButton, Ti...
, })), ); const PaymentMethodConfirmation = enhance(({ onPressEdit }) => ( <BackgroundView> <PaddedView> <Row> <Title>Review</Title> <TinyButton onPress={onPressEdit}> <TinyButtonText>Edit</TinyButtonText> </TinyButton> </Row> </PaddedView> <SavedPaymentRev...
{ props.history.push('address'); }
identifier_body
checkstyleFormatter.d.ts
/** * @license * Copyright 2016 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License");
* http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language govern...
* you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
random_line_split
checkstyleFormatter.d.ts
/** * @license * Copyright 2016 Palantir Technologies, 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 * * Unless required by...
extends AbstractFormatter { static metadata: IFormatterMetadata; format(failures: RuleFailure[]): string; private escapeXml(str); }
Formatter
identifier_name
004-fullscreen.js
/** * @name jQuery FullScreen Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ * @license MIT License */ (function($){ // Adding a new test to the jQuery support object $.support.fullscreen = supportFullScreen(); // Creating t...
else if (elem.webkitRequestFullScreen) { elem.webkitRequestFullScreen(); } } function fullScreenStatus(){ return document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen; } function cancelFullScreen(){ if (document.exitFullscreen) { document.exitFullscreen(); } ...
{ elem.mozRequestFullScreen(); }
conditional_block
004-fullscreen.js
/** * @name jQuery FullScreen Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ * @license MIT License */ (function($){ // Adding a new test to the jQuery support object $.support.fullscreen = supportFullScreen(); // Creating t...
(callback){ $(document).on("fullscreenchange mozfullscreenchange webkitfullscreenchange", function(){ // The full screen status is automatically // passed to our callback as an argument. callback(fullScreenStatus()); }); } })(jQuery);
onFullScreenEvent
identifier_name
004-fullscreen.js
/** * @name jQuery FullScreen Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ * @license MIT License */ (function($){ // Adding a new test to the jQuery support object $.support.fullscreen = supportFullScreen(); // Creating t...
})(jQuery);
{ $(document).on("fullscreenchange mozfullscreenchange webkitfullscreenchange", function(){ // The full screen status is automatically // passed to our callback as an argument. callback(fullScreenStatus()); }); }
identifier_body
004-fullscreen.js
/** * @name jQuery FullScreen Plugin * @author Martin Angelov * @version 1.0 * @url http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/ * @license MIT License */ (function($){ // Adding a new test to the jQuery support object $.support.fullscreen = supportFullScreen(); // Creating t...
function onFullScreenEvent(callback){ $(document).on("fullscreenchange mozfullscreenchange webkitfullscreenchange", function(){ // The full screen status is automatically // passed to our callback as an argument. callback(fullScreenStatus()); }); } })(jQuery);
} else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } }
random_line_split
view.js
/******************************* * 名称:详情 * 作者:rubbish.boy@163.com ******************************* */ //获取应用实例 var app = getApp() var config={ //页面的初始数据 data: { title : '名片介绍', userInfo : {}, session_id :'', requestlock :true, domainName ...
}, //页面相关事件处理函数--监听用户下拉动作 onPullDownRefresh: function() { // Do something when pull down. this.get_info(this.data.dataid,"onPullDownRefresh"); }, //页面上拉触底事件的处理函数 onReachBottom: function() { // Do something when page reach bottom. }, //导航处理函数 bindNavigateTo: function(action) { app.bin...
载 onUnload: function() { // Do something when page close.
conditional_block
view.js
/******************************* * 名称:详情 * 作者:rubbish.boy@163.com ******************************* */ //获取应用实例 var app = getApp() var config={ //页面的初始数据 data: { title : '名片介绍', userInfo : {}, session_id :'', requestlock :true, domainName ...
var msgdata=new Object msgdata.totype=3 msgdata.msg=resback.info app.func.showToast_default(msgdata); //console.log('获取用户登录态失败!' + resback.info); } }) }, //删除请求 del_action:function(action) { var that = this var post_data={token:app.gl...
{ app.action_loading_hidden();
random_line_split
htmldatalistelement.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::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
} } let node: JSRef<Node> = NodeCast::from_ref(self); let filter = box HTMLDataListOptionsFilter; let window = window_from_node(node).root(); HTMLCollection::create(window.r(), node, filter) } }
#[jstraceable] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: JSRef<Element>, _root: JSRef<Node>) -> bool { elem.is_htmloptionelement()
random_line_split
htmldatalistelement.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::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataLi...
(&self) -> bool { *self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement))) } } impl HTMLDataListElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement { ...
is_htmldatalistelement
identifier_name
ocLazyLoad.loaders.common.js
(function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$q", "$window", "$interval", function ($delegate, $q, $window, $interval) { var uaCssChecked = false, useCssLoadPatch ...
var insertBeforeElem = anchor.lastChild; if (params.insertBefore) { var element = angular.element(angular.isDefined(window.jQuery) ? params.insertBefore : document.querySelector(params.insertBefore)); if (element && element.length > 0) { ...
random_line_split
ocLazyLoad.loaders.common.js
(function (angular) { 'use strict'; angular.module('oc.lazyLoad').config(["$provide", function ($provide) { $provide.decorator('$ocLazyLoad', ["$delegate", "$q", "$window", "$interval", function ($delegate, $q, $window, $interval) { var uaCssChecked = false, useCssLoadPatch ...
// Switch in case more content types are added later switch (type) { case 'css': el = $window.document.createElement('link'); el.type = 'text/css'; el.rel = 'stylesheet'; ...
{ filesCache.put(path, deferred.promise); }
conditional_block
getaviprop.py
#!/usr/bin/env python """ gets basic info about AVI file using OpenCV input: filename or cv2.Capture """ from pathlib import Path from struct import pack from typing import Dict, Any import cv2 def getaviprop(fn: Path) -> Dict[str, Any]:
'codec': fourccint2ascii(int(v.get(cv2.CAP_PROP_FOURCC))), } if isinstance(fn, Path): v.release() return vidparam def fourccint2ascii(fourcc_int: int) -> str: """ convert fourcc 32-bit integer code to ASCII """ assert isinstance(fourcc_int, int) return pack('<I', fo...
if isinstance(fn, (str, Path)): # assuming filename fn = Path(fn).expanduser() if not fn.is_file(): raise FileNotFoundError(fn) v = cv2.VideoCapture(str(fn)) if v is None: raise OSError(f'could not read {fn}') else: # assuming cv2.VideoCapture object ...
identifier_body
getaviprop.py
#!/usr/bin/env python """ gets basic info about AVI file using OpenCV input: filename or cv2.Capture """ from pathlib import Path from struct import pack from typing import Dict, Any import cv2 def getaviprop(fn: Path) -> Dict[str, Any]: if isinstance(fn, (str, Path)): # assuming filename
else: # assuming cv2.VideoCapture object v = fn if not v.isOpened(): raise OSError(f'cannot read {fn} probable codec issue') vidparam = { 'nframe': int(v.get(cv2.CAP_PROP_FRAME_COUNT)), 'xy_pixel': ( int(v.get(cv2.CAP_PROP_FRAME_WIDTH)), int(v.get...
fn = Path(fn).expanduser() if not fn.is_file(): raise FileNotFoundError(fn) v = cv2.VideoCapture(str(fn)) if v is None: raise OSError(f'could not read {fn}')
conditional_block
getaviprop.py
#!/usr/bin/env python """ gets basic info about AVI file using OpenCV input: filename or cv2.Capture """ from pathlib import Path from struct import pack from typing import Dict, Any import cv2 def
(fn: Path) -> Dict[str, Any]: if isinstance(fn, (str, Path)): # assuming filename fn = Path(fn).expanduser() if not fn.is_file(): raise FileNotFoundError(fn) v = cv2.VideoCapture(str(fn)) if v is None: raise OSError(f'could not read {fn}') else: # assumi...
getaviprop
identifier_name
getaviprop.py
#!/usr/bin/env python """ gets basic info about AVI file using OpenCV input: filename or cv2.Capture """
from pathlib import Path from struct import pack from typing import Dict, Any import cv2 def getaviprop(fn: Path) -> Dict[str, Any]: if isinstance(fn, (str, Path)): # assuming filename fn = Path(fn).expanduser() if not fn.is_file(): raise FileNotFoundError(fn) v = cv2.VideoCap...
random_line_split
history-manager.ts
import { EventEmitter } from "@angular/core"; interface Actions{ undo: () => void; redo: () => void; } export class HistoryManager { commands: Actions[] = []; indexChanged = new EventEmitter<number>(); currentIdx = -1; limit = 0; private execute(command: Actions , actionName: string){ command[actionNa...
this.currentIdx += 1; this.indexChanged.emit(this.currentIdx); } hasUndo(){ return this.currentIdx > -1; } hasRedo(){ return this.currentIdx < (this.commands.length - 1); } setLimit(limit: number): void{ this.limit = limit; } clearHistory(){ this.commands = []; this.currentI...
{ this.execute(command, "redo"); }
conditional_block
history-manager.ts
import { EventEmitter } from "@angular/core"; interface Actions{ undo: () => void; redo: () => void; } export class HistoryManager { commands: Actions[] = []; indexChanged = new EventEmitter<number>(); currentIdx = -1; limit = 0; private execute(command: Actions , actionName: string){ command[actionNa...
(){ const command = this.commands[this.currentIdx+1]; if (command){ this.execute(command, "redo"); } this.currentIdx += 1; this.indexChanged.emit(this.currentIdx); } hasUndo(){ return this.currentIdx > -1; } hasRedo(){ return this.currentIdx < (this.commands.length - 1); } ...
redo
identifier_name
history-manager.ts
import { EventEmitter } from "@angular/core"; interface Actions{ undo: () => void; redo: () => void; } export class HistoryManager { commands: Actions[] = []; indexChanged = new EventEmitter<number>(); currentIdx = -1; limit = 0; private execute(command: Actions , actionName: string){ command[actionNa...
}
{ this.commands = []; this.currentIdx = -1; }
identifier_body
history-manager.ts
import { EventEmitter } from "@angular/core"; interface Actions{ undo: () => void; redo: () => void; } export class HistoryManager { commands: Actions[] = []; indexChanged = new EventEmitter<number>(); currentIdx = -1; limit = 0; private execute(command: Actions , actionName: string){ command[actionNa...
} undo(){ const command = this.commands[this.currentIdx]; if (command){ this.execute(command, "undo"); } this.currentIdx -= 1; this.indexChanged.emit(this.currentIdx); } redo(){ const command = this.commands[this.currentIdx+1]; if (command){ this.execute(command, "redo");...
this.indexChanged.emit(this.currentIdx);
random_line_split
package.py
# -*- coding: utf-8 -*- # # Copyright 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should hav...
def search(self, query, repoId): path = "/api/repositories/%s/packages/search" % repoId pack_list = self.server.GET(path, {"search": query})[1] return pack_list
path = "/api/repositories/%s/packages" % repoId pack_list = self.server.GET(path)[1] return pack_list
random_line_split
package.py
# -*- coding: utf-8 -*- # # Copyright 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should hav...
(self, repoId): path = "/api/repositories/%s/packages" % repoId pack_list = self.server.GET(path)[1] return pack_list def search(self, query, repoId): path = "/api/repositories/%s/packages/search" % repoId pack_list = self.server.GET(path, {"search": query})[1] retur...
packages_by_repo
identifier_name
package.py
# -*- coding: utf-8 -*- # # Copyright 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should hav...
path = "/api/repositories/%s/packages/search" % repoId pack_list = self.server.GET(path, {"search": query})[1] return pack_list
identifier_body
submit_batch.py
#!/usr/bin/env python3 # coding: utf-8 import BRT from collections import namedtuple import configparser import os import logging from os.path import expanduser import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--submit', help='Execute the submission', action='store_true') parser.add_argu...
(*ar, **kwar): if args.verbose and not args.quiet: print(*ar, **kwar) obslst=[ VStar('S Ori', comm='Mira AAVSO', expos=120), VStar('CH Cyg', comm='Symbiotic AAVSO', expos=60), VStar('SS Cyg', comm='Mira', expos=180), VStar('EU Cyg', comm='Mira', expos=180), VStar('IP Cyg', comm='Mira',...
vprint
identifier_name
submit_batch.py
#!/usr/bin/env python3 # coding: utf-8 import BRT from collections import namedtuple import configparser import os import logging from os.path import expanduser import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--submit', help='Execute the submission', action='store_true') parser.add_argu...
obslst=[ VStar('S Ori', comm='Mira AAVSO', expos=120), VStar('CH Cyg', comm='Symbiotic AAVSO', expos=60), VStar('SS Cyg', comm='Mira', expos=180), VStar('EU Cyg', comm='Mira', expos=180), VStar('IP Cyg', comm='Mira', expos=180), VStar('V686 Cyg', comm='Mira', expos=180), #VStar('AS Lac', ...
if args.verbose and not args.quiet: print(*ar, **kwar)
identifier_body
submit_batch.py
#!/usr/bin/env python3 # coding: utf-8 import BRT from collections import namedtuple import configparser import os import logging from os.path import expanduser import argparse parser = argparse.ArgumentParser() parser.add_argument('-s', '--submit', help='Execute the submission', action='store_true') parser.add_argu...
qprint() else : qprint('No missing jobs. Nothing to do!') log.info('Done.')
qprint(f' Failure:{i}', end='')
conditional_block
submit_batch.py
#!/usr/bin/env python3 # coding: utf-8 import BRT from collections import namedtuple import configparser import os import logging from os.path import expanduser import argparse parser = argparse.ArgumentParser()
parser.add_argument('-s', '--submit', help='Execute the submission', action='store_true') parser.add_argument('-q', '--quiet', help='Jast do the job. Stay quiet', action='store_true') parser.add_argument('-v', '--verbose', help='Print more status info', action='store_true') parser.add_argument('-d', '--debug', help='Pr...
random_line_split
SocialNW.py
#!/usr/bin/python # # Author: Rajesh Sinha, Karan Narain # The base class for Twitter and GPlus Objects # import logging import sys from bs4 import BeautifulSoup import urllib2 import re ## Some Important constants _parser = "lxml" ## remember to pip install lxml or else use another parser _loggingLevel = loggin...
self.logger.info('Found %d Unique Posters for the link', len(posters)) for poster in posters: print (poster).encode('utf-8') self.logger.info('written all the posters to stdout...') else: self.logger.error('found error in URL upfront so bailing out...
random_line_split
SocialNW.py
#!/usr/bin/python # # Author: Rajesh Sinha, Karan Narain # The base class for Twitter and GPlus Objects # import logging import sys from bs4 import BeautifulSoup import urllib2 import re ## Some Important constants _parser = "lxml" ## remember to pip install lxml or else use another parser _loggingLevel = loggin...
self.logger.info('written all the posters to stdout...') else: self.logger.error('found error in URL upfront so bailing out') sys.stderr.flush() sys.stdout.flush() sys.exit(1)
print (poster).encode('utf-8')
conditional_block
SocialNW.py
#!/usr/bin/python # # Author: Rajesh Sinha, Karan Narain # The base class for Twitter and GPlus Objects # import logging import sys from bs4 import BeautifulSoup import urllib2 import re ## Some Important constants _parser = "lxml" ## remember to pip install lxml or else use another parser _loggingLevel = loggin...
(self, page): return page.geturl() == self.baseLink @staticmethod def isValidURL(url): testUrl = 'https://www.altmetric.com/details/' + url regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(...
isRedirect
identifier_name
SocialNW.py
#!/usr/bin/python # # Author: Rajesh Sinha, Karan Narain # The base class for Twitter and GPlus Objects # import logging import sys from bs4 import BeautifulSoup import urllib2 import re ## Some Important constants _parser = "lxml" ## remember to pip install lxml or else use another parser _loggingLevel = loggin...
def openAndLoadURL(self, fname): """ Opens the base URL for a network and returns the beautifulSoup through lxml parses """ self.logger.debug('Opening URL ' + fname) try: page = urllib2.urlopen(fname) except urllib2.HTTPError, e: self.logger.error('Could not ...
testUrl = 'https://www.altmetric.com/details/' + url regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{...
identifier_body