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 |
|---|---|---|---|---|
coerce-date-property.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DateAdapter} from '@angular/material/core';
/**
* Function that attempts to coerce a value to a date using... | <D>(adapter: DateAdapter<D>, value: any): D | null {
if (typeof value === 'string') {
if (value == '') {
value = null;
} else {
value = adapter.fromIso8601(value) || value;
}
}
if (value == null || adapter.isDateInstance(value)) {
return value;
}
throw Error(`Datepicker: Value must... | coerceDateProperty | identifier_name |
coerce-date-property.ts | /**
* @license | */
import {DateAdapter} from '@angular/material/core';
/**
* Function that attempts to coerce a value to a date using a DateAdapter. Date instances, null,
* and undefined will be passed through. Empty strings will be coerced to null. Valid ISO 8601
* strings (https://www.ietf.org/rfc/rfc3339.txt) will be coerced... | * Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license | random_line_split |
coerce-date-property.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DateAdapter} from '@angular/material/core';
/**
* Function that attempts to coerce a value to a date using... | {
if (typeof value === 'string') {
if (value == '') {
value = null;
} else {
value = adapter.fromIso8601(value) || value;
}
}
if (value == null || adapter.isDateInstance(value)) {
return value;
}
throw Error(`Datepicker: Value must be either a date object recognized by the DateAdap... | identifier_body | |
actioninput.js | // This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
(function($) {
'use strict';
$.widget('indico.actioninput', $.indico.clearableinput, {
opti... |
});
self.buttonBox.prepend(self.actionIcon);
input.addClass('actionabletext');
},
_action: function() {
var self = this;
var opt = self.options;
var input = self.element;
opt.actionCallback();
if (opt.focusOnClear) {
input.focus();
} else {
... | {
self._action();
} | conditional_block |
actioninput.js | // This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
(function($) {
'use strict';
| actionIcon: 'icon-checkmark',
alwaysClearable: true,
enterKeyEnabled: true,
},
_create: function() {
var self = this;
var input = self.element;
self._super();
self.actionIcon = $(
'<a class="i-link accept hide-if-locked {0}"></a>'.format(self.options.actionIc... | $.widget('indico.actioninput', $.indico.clearableinput, {
options: {
actionCallback: function() {}, | random_line_split |
validator.py | import urllib.parse
from upol_search_engine.upol_crawler.tools import blacklist, robots
def validate_regex(url, regex):
"""Check if url is validate with regex"""
return regex.match(url)
def validate_anchor(url):
"""Check if url include anchor"""
cheme, netloc, path, qs, anchor = urllib.parse.urlspl... | """Complete validator"""
if not validate_anchor(url):
return False, 'UrlHasAnchor'
if not validate_regex(url, regex):
return False, 'UrlInvalidRegex'
if blacklist.is_url_blocked(url, blacklist_list):
return False, 'UrlIsBlacklisted'
if not robots.is_crawler_allowed(url):
... | identifier_body | |
validator.py | import urllib.parse
from upol_search_engine.upol_crawler.tools import blacklist, robots
def validate_regex(url, regex):
"""Check if url is validate with regex"""
return regex.match(url)
def validate_anchor(url):
"""Check if url include anchor"""
cheme, netloc, path, qs, anchor = urllib.parse.urlspl... | (url, regex, blacklist_list):
"""Complete validator"""
if not validate_anchor(url):
return False, 'UrlHasAnchor'
if not validate_regex(url, regex):
return False, 'UrlInvalidRegex'
if blacklist.is_url_blocked(url, blacklist_list):
return False, 'UrlIsBlacklisted'
if not rob... | validate | identifier_name |
validator.py | import urllib.parse
from upol_search_engine.upol_crawler.tools import blacklist, robots
def validate_regex(url, regex):
"""Check if url is validate with regex"""
return regex.match(url)
def validate_anchor(url): | cheme, netloc, path, qs, anchor = urllib.parse.urlsplit(url)
if anchor:
return False
else:
return True
def validate_phpbb(url):
"""Validate if url from phpBB system is valid or blacklisted"""
scheme, netloc, path, qs, anchor = urllib.parse.urlsplit(url)
path = path + qs + ancho... | """Check if url include anchor""" | random_line_split |
validator.py | import urllib.parse
from upol_search_engine.upol_crawler.tools import blacklist, robots
def validate_regex(url, regex):
"""Check if url is validate with regex"""
return regex.match(url)
def validate_anchor(url):
"""Check if url include anchor"""
cheme, netloc, path, qs, anchor = urllib.parse.urlspl... |
def validate_phpbb(url):
"""Validate if url from phpBB system is valid or blacklisted"""
scheme, netloc, path, qs, anchor = urllib.parse.urlsplit(url)
path = path + qs + anchor
url_keywords = ['posting.php',
'ucp.php',
'view=print',
'member... | return True | conditional_block |
esr_from.rs | /*
This file is a part of cargo-esr.
Copyright (C) 2017 Mohammad AlSaleh <CE.Mohammad.AlSaleh at gmail.com>
https://github.com/rust-alt/cargo-esr
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 ca... | // url=id by default
fn url_from_id(id: &str) -> String {
String::from(id)
}
fn url_from_id_and_token(id: &str, token: &str) -> String {
let url = Self::url_from_id(id);
if url.find('?').is_some() {
url + "&access_token=" + token
} else {
url + "?... | pub trait EsrFrom: Sized + Sync + Send + DeserializeOwned { | random_line_split |
esr_from.rs | /*
This file is a part of cargo-esr.
Copyright (C) 2017 Mohammad AlSaleh <CE.Mohammad.AlSaleh at gmail.com>
https://github.com/rust-alt/cargo-esr
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 ca... |
#[derive(Deserialize, Debug, Clone)]
pub struct Meta {
pub total: usize,
}
#[async_trait]
pub trait EsrFromMulti: EsrFrom + Sync + Send + 'static {
type Inner: Clone;
async fn from_url_multi(url: &str, multi_page: bool) -> Result<Self> {
let mut initial_self = Self::from_url(url).await?;
... | {
static RET: OnceCell<HttpClient> = OnceCell::new();
let init = || HttpClientBuilder::new()
//.connect_timeout(Duration::from_secs(5))
.max_connections(32)
.redirect_policy(RedirectPolicy::Limit(5))
.auto_referer()
.default_header("User-Agent", "cargo-esr/0.1")
.... | identifier_body |
esr_from.rs | /*
This file is a part of cargo-esr.
Copyright (C) 2017 Mohammad AlSaleh <CE.Mohammad.AlSaleh at gmail.com>
https://github.com/rust-alt/cargo-esr
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 ca... |
}
async fn bytes_from_url(url: &str) -> Result<Vec<u8>> {
let client = get_static_client()?;
log::debug!("Getting data from '{}'", url);
// Creating an outgoing request.
let mut response = client.get_async(url).await?;
let mut buf = Vec::with_capacity(64*1024);
... | {
url + "?access_token=" + token
} | conditional_block |
esr_from.rs | /*
This file is a part of cargo-esr.
Copyright (C) 2017 Mohammad AlSaleh <CE.Mohammad.AlSaleh at gmail.com>
https://github.com/rust-alt/cargo-esr
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 ca... | (id: &str, token: &str) -> Result<Vec<u8>> {
Self::bytes_from_url(&*Self::url_from_id_and_token(id, token)).await
}
fn from_bytes(bytes: &[u8]) -> Result<Self> {
// Deserialize
let info = serde_json::from_slice(bytes)?;
Ok(info)
}
async fn from_url(url: &str) -> Result<... | bytes_from_id_with_token | identifier_name |
__init__.py | ", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam])
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligne... | (in_bam, data, target_counts, read_filter="", always_run=False,
work_dir=None):
"""Downsample a BAM file to the specified number of target counts.
"""
index(in_bam, data["config"])
ds_pct = get_downsample_pct(in_bam, target_counts, data)
if always_run and not ds_pct:
ds_pct = ... | downsample | identifier_name |
__init__.py | ", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam])
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligne... |
else:
samtools = config_utils.get_program("samtools", config)
cmd = ("{samtools} view -c {in_bam}").format(**locals())
out = subprocess.check_output(cmd, shell=True)
return int(out)
def sam_to_bam(in_sam, config):
if is_bam(in_sam):
return in_sam
assert is_sam(in_sam), "%... | cmd = ("{sambamba} view -c {in_bam}").format(**locals()) | conditional_block |
__init__.py | ", data["config"])
idxstats_out = subprocess.check_output([samtools, "idxstats", in_bam])
out = []
for line in idxstats_out.split("\n"):
if line.strip():
contig, length, aligned, unaligned = line.split("\t")
out.append(AlignInfo(contig, int(length), int(aligned), int(unaligne... | if is_bam(in_sam):
return in_sam
assert is_sam(in_sam), "%s is not a SAM file" % in_sam
out_file = os.path.splitext(in_sam)[0] + ".bam"
if utils.file_exists(out_file):
return out_file
samtools = config_utils.get_program("samtools", config)
num_cores = config["algorithm"].get("n... |
def sam_to_bam(in_sam, config): | random_line_split |
__init__.py | if not config:
config = {}
sambamba = _get_sambamba(config)
if sambamba:
cmd = ("{sambamba} view -c {in_bam}").format(**locals())
else:
samtools = config_utils.get_program("samtools", config)
cmd = ("{samtools} view -c {in_bam}").format(**locals())
out = subprocess.check... | SUFFIXES = {"coordinate": ".sorted", "queryname": ".nsorted"}
sort_base = os.path.splitext(in_bam)[0]
for suffix in SUFFIXES:
sort_base = sort_base.split(suffix)[0]
return sort_base + SUFFIXES[order] | identifier_body | |
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... | fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::fro... | impl ToCss for SpecifiedValue { | random_line_split |
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... |
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<Specifie... | {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
... | identifier_body |
list.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${help... | (pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
... | T | identifier_name |
spec.js | // This file defines an API that would be nice, but it's not required
// Initialize the editor
var editor = new Editor("");
// Activate/deactivate the editor
editor.active(true || false);
// Set a new action
editor.add("", {
shortcut: {} || "" || false, // The key for Ctrl+key or { key: "esc" }
menu: {} || ... |
// Some key is introduced (for example, "tab")
editor.on("key", function(){});
editor.on("select", function(){});
// Special events
editor.on("<event>:before", function(){});
editor.on("<event>:pre", function(){});
editor.on("<event>:post", function(){});
editor.on("<event>:after", function(){});
editor.on("<event>... | // The editor re-reads its data
editor.on("refresh", function(){});
// Some part of the editor is clicked or touched
editor.on("click", function(){}); | random_line_split |
validations.js | /*
This file is part of Ext JS 4
Copyright (c) 2011 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the p... | * @type String
*/
inclusionMessage: 'is not included in the list of acceptable values',
/**
* The default error message used when an exclusion validation fails
* @property exclusionMessage
* @type String
*/
exclusionMessage: 'is not an acceptable value',
/**
... | * @property inclusionMessage | random_line_split |
validations.js | /*
This file is part of Ext JS 4
Copyright (c) 2011 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the p... |
},
/**
* Returns true if the given value passes validation against the configured {@link #matcher} regex
* @param {Object} config Optional config object
* @param {String} value The value to validate
* @return {Boolean} True if the value passes the format validation
*/
format: ... | {
return true;
} | conditional_block |
units.py | I = complex(0,1)
ha2ev = 27.211396132
ev2cm1 = 8065.5440044136285
bohr2ang = 0.52917720859 | 10.811, 12.0107, 14.0067, 15.9994, 18.9984032,
20.1797, 22.98976928, 24.305,26.9815386, 28.0855,
30.973762, 32.065, 35.453, 39.948, 39.0983,
40.078, 44.955912, 47.867, 50.9415, 51.9961,
54.938045, ... |
atomic_mass = [ None, 1.00794, 4.002602, 6.941, 9.012182, | random_line_split |
code1a.py | # coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
"""
Konstruktor planszy do gry. Przygotowuje okienko gry.
:param width: szerokość w pikselach
... | lenia czy komórka jest żywa
DEAD = 0
ALIVE = 1
class Population(object):
"""
Populacja komórek
"""
def __init__(self, width, height, cell_size=10):
"""
Przygotowuje ustawienia populacji
:param width: szerokość planszy mierzona liczbą komórek
:param heig... | mowych, tutaj zinterpretujemy np. ruchy myszką
:return True jeżeli pygame przekazał zdarzenie wyjścia z gry
"""
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
pygame.quit()
return True
# magiczne liczby używane do ok... | identifier_body |
code1a.py | # coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
"""
Konstruktor planszy do gry. Przygotowuje okienko gry.
:param width: szerokość w pikselach
... | o tym jak wszystkie klasy zostaną zadeklarowane
if __name__ == "__main__":
game = GameOfLife(80, 40)
game.run()
| dopiero p | conditional_block |
code1a.py | # coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
"""
Konstruktor planszy do gry. Przygotowuje okienko gry.
:param width: szerokość w pikselach
... | game.run() |
# Ta część powinna być zawsze na końcu modułu (ten plik jest modułem)
# chcemy uruchomić naszą grę dopiero po tym jak wszystkie klasy zostaną zadeklarowane
if __name__ == "__main__":
game = GameOfLife(80, 40)
| random_line_split |
code1a.py | # coding=utf-8
import pygame
import pygame.locals
class Board(object):
"""
Plansza do gry. Odpowiada za rysowanie okna gry.
"""
def __init__(self, width, height):
"""
Konstruktor planszy do gry. Przygotowuje okienko gry.
:param width: szerokość w pikselach
... | """
def __init__(self, width, height, cell_size=10):
"""
Przygotowuje ustawienia populacji
:param width: szerokość planszy mierzona liczbą komórek
:param height: wysokość planszy mierzona liczbą komórek
:param cell_size: bok komórki w pikselach
"""
... | komórek
| identifier_name |
beanTree.js | angular.module('jolokiaWeb').filter('beanTree', function() {
function extractBean(beanPath){
// beanPath: type=Valve,host=localhost,context=/,name=NonLoginAuthenticator
var result = [];
var parts = beanPath.split(',');
parts.forEach(function(p){
var subPart = p.split("=... | (str){
if (str === "[J") { return "long[]"; }
else if (str.startsWith("[L") && str.endsWith(";")) {
return str.replace(/^\[L/, "").replace(/;$/,"") + "[]";
}
return str;
}
function sortTree(arr) {
arr = _.sortBy(arr, 'name');
arr.forEach(function(item... | getTypeName | identifier_name |
beanTree.js | angular.module('jolokiaWeb').filter('beanTree', function() {
function extractBean(beanPath){
// beanPath: type=Valve,host=localhost,context=/,name=NonLoginAuthenticator
var result = [];
var parts = beanPath.split(',');
parts.forEach(function(p){
var subPart = p.split("=... | currentPathNode = existingNode;
// If this is the last path segment then this is an MBean with a child MBean in the tree
if (bean.pathArr.length-1 == i){
currentPathNode = fillAll(currentPathNode, bean);
... | var existingNode = _.findWhere(currentPathNode.children, {id: pathId});
if (existingNode) {
// already registered path node | random_line_split |
beanTree.js | angular.module('jolokiaWeb').filter('beanTree', function() {
function extractBean(beanPath){
// beanPath: type=Valve,host=localhost,context=/,name=NonLoginAuthenticator
var result = [];
var parts = beanPath.split(',');
parts.forEach(function(p){
var subPart = p.split("=... |
function sortTree(arr) {
arr = _.sortBy(arr, 'name');
arr.forEach(function(item){
item.children = sortTree(item.children);
});
return arr;
}
function fillAll(node, bean){
node = fillBasicInfo(node,bean);
node = fillAttributes(node,bean);
... | {
if (str === "[J") { return "long[]"; }
else if (str.startsWith("[L") && str.endsWith(";")) {
return str.replace(/^\[L/, "").replace(/;$/,"") + "[]";
}
return str;
} | identifier_body |
beanTree.js | angular.module('jolokiaWeb').filter('beanTree', function() {
function extractBean(beanPath){
// beanPath: type=Valve,host=localhost,context=/,name=NonLoginAuthenticator
var result = [];
var parts = beanPath.split(',');
parts.forEach(function(p){
var subPart = p.split("=... | if (bean.pathArr.length-1 == i){
insertNode = fillAll(insertNode, bean);
}
currentPathNode.children.push(insertNode);
currentPathNode = insertNode;
}
}
... | {
pathId += ((i==0) ? "" : ",") + bean.pathArr[i].join("=");
var existingNode = _.findWhere(currentPathNode.children, {id: pathId});
if (existingNode) {
// already registered path node
currentPathNode = existing... | conditional_block |
comments.rs | ("/**") && is_block_doc_comment(s)) ||
s.starts_with("/*!")
}
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comm... |
if rdr.curr_is('\n') {
trim_whitespace_prefix_and_push_line(&mut lines,
curr_line,
col);
curr_line = String::new();
rdr.bump();
} else {
... | {
rdr.fatal("unterminated block comment");
} | conditional_block |
comments.rs | : &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> String {
/// remove whitespace-only lines from the start/end o... | pub pos: BytePos,
}
// it appears this function is called only from pprust... that's
// probably not a good thing. | random_line_split | |
comments.rs | >>> shebang comment");
let p = rdr.last_pos;
debug!("<<< shebang comment");
comments.push(Comment {
style: if code_to_the_left { Trailing } else { Isolated },
lines: vec!(rdr.read_one_line_comment()),
pos: p
});
}
fn read_line_comments(rdr: &mut StringReader, code_to_the_left: b... | {
let stripped = strip_doc_comment_decoration("/// test");
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration("///! test");
assert_eq!(stripped, " test");
let stripped = strip_doc_comment_decoration("// test");
assert_eq!(stripped, " test");
... | identifier_body | |
comments.rs | ELINERS {
if comment.starts_with(*prefix) {
return (&comment[prefix.len()..]).to_string();
}
}
if comment.starts_with("/*") {
let lines = comment[3..comment.len() - 2]
.lines_any()
.map(|s| s.to_string())
.collect::<Vec<String> >();
... | test_block_doc_comment_3 | identifier_name | |
race.rs | use gen::{Generator, GenResult, Yields, Returns};
use gen::either::GenEither;
use cat::sum::Either;
use cat::{Iso, Inj};
pub struct GenRace<F, L>(GenEither<(F, L), (F, L)>);
impl<F, L> Yields for GenRace<F, L>
where F: Yields
{
type Yield = F::Yield;
}
impl<F, L> Returns for GenRace<F, L>
where F: Retur... |
GenEither::Latter((f, l)) => {
match l.next().inj() {
Either::Left(s) => {
let (y, l) = s.inj();
GenResult::Yield(y, GenRace(GenEither::Former((f, l))))
}
Either::Right(l) => GenResul... | {
match f.next().inj() {
Either::Left(s) => {
let (y, f) = s.inj();
GenResult::Yield(y, GenRace(GenEither::Latter((f, l))))
}
Either::Right(f) => GenResult::Return(GenEither::Former((f, l))),
... | conditional_block |
race.rs | use gen::{Generator, GenResult, Yields, Returns};
use gen::either::GenEither;
use cat::sum::Either;
use cat::{Iso, Inj};
pub struct GenRace<F, L>(GenEither<(F, L), (F, L)>);
impl<F, L> Yields for GenRace<F, L>
where F: Yields
{
type Yield = F::Yield;
}
impl<F, L> Returns for GenRace<F, L>
where F: Retur... | (self) -> GenResult<Self> {
match self.0 {
GenEither::Former((f, l)) => {
match f.next().inj() {
Either::Left(s) => {
let (y, f) = s.inj();
GenResult::Yield(y, GenRace(GenEither::Latter((f, l))))
... | next | identifier_name |
race.rs | use gen::{Generator, GenResult, Yields, Returns};
use gen::either::GenEither;
use cat::sum::Either;
use cat::{Iso, Inj};
pub struct GenRace<F, L>(GenEither<(F, L), (F, L)>);
impl<F, L> Yields for GenRace<F, L>
where F: Yields
{
type Yield = F::Yield;
}
impl<F, L> Returns for GenRace<F, L>
where F: Retur... | }
}
}
pub trait Race
{
fn race<L>(self, l: L) -> GenRace<Self, L> where Self: Sized
{
GenRace(GenEither::Former((self, l)))
}
}
impl<C> Race for C {}
#[cfg(test)]
mod tests {
use gen::iter::wrap::Wrap;
use gen::map::ret::MapReturn;
use gen::comb::race::Race;
use gen... | {
match self.0 {
GenEither::Former((f, l)) => {
match f.next().inj() {
Either::Left(s) => {
let (y, f) = s.inj();
GenResult::Yield(y, GenRace(GenEither::Latter((f, l))))
}
Eith... | identifier_body |
race.rs | use gen::{Generator, GenResult, Yields, Returns};
use gen::either::GenEither;
use cat::sum::Either;
use cat::{Iso, Inj};
pub struct GenRace<F, L>(GenEither<(F, L), (F, L)>);
impl<F, L> Yields for GenRace<F, L>
where F: Yields
{
type Yield = F::Yield; |
impl<F, L> Returns for GenRace<F, L>
where F: Returns,
L: Returns
{
type Return = GenEither<(F::Return, L), (F, L::Return)>;
}
impl<F, L> Generator for GenRace<F, L>
where F: Generator,
L: Generator<Yield = F::Yield>,
L::Transition: Iso<Either<(F::Yield, L), L::Return>>,
{
... | } | random_line_split |
SandHTMLElement.ts | import { Resolve, Type } from '@ephox/katamari';
| const getPrototypeOf = Object.getPrototypeOf;
/*
* IE9 and above
*
* MDN no use on this one, but here's the link anyway:
* https://developer.mozilla.org/en/docs/Web/API/HTMLElement
*/
const sandHTMLElement = (scope: Window) => {
return Global.getOrDie('HTMLElement', scope) as typeof HTMLElement;
};
const isPro... | import * as Global from '../util/Global';
| random_line_split |
subst.rs | {
ErasedRegions => ErasedRegions,
NonerasedRegions(r) => NonerasedRegions(op(r, a))
}
}
pub fn is_erased(&self) -> bool {
match *self {
ErasedRegions => true,
NonerasedRegions(_) => false,
}
}
}
//////////////////////////////////////... | is_empty | identifier_name | |
subst.rs | uint, self_limit: uint)
-> VecPerParamSpace<T>
{
VecPerParamSpace {
type_limit: type_limit,
self_limit: self_limit,
content: content,
}
}
/// Appends `value` to the vector associated with `space`.
///
/// Unlike the `push` met... | }
impl<'tcx, T:TypeFoldable<'tcx>> Subst<'tcx> for T {
fn subst_spanned(&self, | random_line_split | |
subst.rs | .limits(space);
if start == limit {
None
} else {
match space {
TypeSpace => { self.type_limit -= 1; self.self_limit -= 1; }
SelfSpace => { self.self_limit -= 1; }
FnSpace => {}
}
if self.content.is_empty() {... | {
self.region_binders_passed += 1;
} | identifier_body | |
INetworkReachabilityCallbackError.ts | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi... | (object : any) : INetworkReachabilityCallbackError {
var retValue : INetworkReachabilityCallbackError = INetworkReachabilityCallbackError.Unknown;
if (object != null && object.value != null && INetworkReachabilityCallbackError.hasOwnProperty(object.value)) {
retValue = ... | toObject | identifier_name |
INetworkReachabilityCallbackError.ts | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi... |
/**
@property {Adaptive.INetworkReachabilityCallbackError} [Forbidden='Forbidden']
*/
static Forbidden = new INetworkReachabilityCallbackError("Forbidden");
/**
@property {Adaptive.INetworkReachabilityCallbackError} [NotFound='NotFound']
*/
... | {return this.value;} | identifier_body |
INetworkReachabilityCallbackError.ts | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi... |
module Adaptive {
/**
@enum {Adaptive.INetworkReachabilityCallbackError} Adaptive.INetworkReachabilityCallbackError
Enumeration INetworkReachabilityCallbackError
*/
export class INetworkReachabilityCallbackError {
constructor(public value:string){}
toString(){return... |
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/ | random_line_split |
INetworkReachabilityCallbackError.ts | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi... |
return retValue;
}
}
}
| {
retValue = INetworkReachabilityCallbackError[object.value];
} | conditional_block |
up_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# 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 restrictio... | # Keyboard accelerator:
accelerator = "Alt+Up"
# The action's image (displayed on tool bar tools etc):
image = ImageResource("up", search_path=[IMAGE_LOCATION])
#--------------------------------------------------------------------------
# "UpAction" interface:
#---------------------------... | random_line_split | |
up_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# 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 restrictio... | (self, event):
""" Perform the action.
"""
# Note that we always offer the service via its name, but look it up
# via the actual protocol.
from puddle.resource.i_workspace import IWorkspace
workspace = self.window.application.get_service(IWorkspace)
workspace.pat... | perform | identifier_name |
up_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# 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 restrictio... |
# EOF -------------------------------------------------------------------------
| workspace = self.window.application.get_service(IWorkspace)
view.tree_viewer.refresh(workspace) | conditional_block |
up_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# 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 restrictio... |
# EOF -------------------------------------------------------------------------
| """ Perform the action.
"""
# Note that we always offer the service via its name, but look it up
# via the actual protocol.
from puddle.resource.i_workspace import IWorkspace
workspace = self.window.application.get_service(IWorkspace)
workspace.path = dirname(workspace.a... | identifier_body |
user.ts | /* tslint:disable */
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toArray';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of... | extends BaseEffects {
@Effect()
protected login: Observable<Action> = this.actions$
.ofType(UserActionTypes.LOGIN)
.map(toPayload)
.mergeMap((payload) =>
this.user.login(payload.credentials, payload.include, payload.rememberMe)
.map((response) => new UserActions.loginSuccess(response))
... | UserEffects | identifier_name |
user.ts | /* tslint:disable */
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toArray';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of... |
}
| {
super(actions$, user, 'Account', UserActionTypes);
} | identifier_body |
user.ts | /* tslint:disable */
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/toArray';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of... | .map(toPayload)
.mergeMap((payload) =>
this.user.create(payload.credentials)
.map((response) => new UserActions.registerSuccess(response))
.catch((error) => concat(
of(new UserActions.registerFail(error)),
of(new ErrorActions.error(error))
))
);
@Effect()... | .ofType(UserActionTypes.REGISTER) | random_line_split |
enum_same_crate_empty_match.rs | #![deny(unreachable_patterns)]
#[non_exhaustive]
pub enum NonExhaustiveEnum {
Unit,
//~^ not covered
Tuple(u32),
//~^ not covered
Struct { field: u32 }
//~^ not covered
}
pub enum NormalEnum {
Unit,
//~^ not covered
Tuple(u32),
//~^ not covered
Struct { field: u32 } | pub enum EmptyNonExhaustiveEnum {}
fn empty_non_exhaustive(x: EmptyNonExhaustiveEnum) {
match x {}
match x {
_ => {} //~ ERROR unreachable pattern
}
}
fn main() {
match NonExhaustiveEnum::Unit {}
//~^ ERROR `Unit`, `Tuple(_)` and `Struct { .. }` not covered [E0004]
match NormalEnum::Un... | //~^ not covered
}
#[non_exhaustive] | random_line_split |
enum_same_crate_empty_match.rs | #![deny(unreachable_patterns)]
#[non_exhaustive]
pub enum NonExhaustiveEnum {
Unit,
//~^ not covered
Tuple(u32),
//~^ not covered
Struct { field: u32 }
//~^ not covered
}
pub enum NormalEnum {
Unit,
//~^ not covered
Tuple(u32),
//~^ not covered
Struct { field: u32 }
//~... | {}
fn empty_non_exhaustive(x: EmptyNonExhaustiveEnum) {
match x {}
match x {
_ => {} //~ ERROR unreachable pattern
}
}
fn main() {
match NonExhaustiveEnum::Unit {}
//~^ ERROR `Unit`, `Tuple(_)` and `Struct { .. }` not covered [E0004]
match NormalEnum::Unit {}
//~^ ERROR `Unit`, `T... | EmptyNonExhaustiveEnum | identifier_name |
SearchHelper.ts | /**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ISearchHelper, ISearchAddonTerminal } from './Interfaces';
interface ISearchResult {
term: string;
col: number;
row: number;
}
/**
* A class that knows how to search the terminal and how to display the results.
... | }
}
return {
term,
col: searchIndex,
row: y
};
}
}
/**
* Selects and scrolls to a result.
* @param result The result to select.
* @return Whethera result was selected.
*/
private _selectResult(result: ISearchResult): boolean {
if (!result) {
... | // Adjust the searchIndex for empty characters following wide unicode
// chars (eg. CJK)
const charWidth = charData[2/*CHAR_DATA_WIDTH_INDEX*/];
if (charWidth === 0) {
searchIndex++; | random_line_split |
SearchHelper.ts | /**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ISearchHelper, ISearchAddonTerminal } from './Interfaces';
interface ISearchResult {
term: string;
col: number;
row: number;
}
/**
* A class that knows how to search the terminal and how to display the results.
... | (private _terminal: ISearchAddonTerminal) {
// TODO: Search for multiple instances on 1 line
// TODO: Don't use the actual selection, instead use a "find selection" so multiple instances can be highlighted
// TODO: Highlight other instances in the viewport
// TODO: Support regex, case sensitivity, etc.
... | constructor | identifier_name |
SearchHelper.ts | /**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ISearchHelper, ISearchAddonTerminal } from './Interfaces';
interface ISearchResult {
term: string;
col: number;
row: number;
}
/**
* A class that knows how to search the terminal and how to display the results.
... |
// Search from the top to the current ydisp
if (!result) {
for (let y = 0; y < startRow; y++) {
result = this._findInLine(term, y);
if (result) {
break;
}
}
}
// Set selection and scroll if a result was found
return this._selectResult(result);
}
... | {
if (!term || term.length === 0) {
return false;
}
let result: ISearchResult;
let startRow = this._terminal.buffer.ydisp;
if (this._terminal.selectionManager.selectionEnd) {
// Start from the selection end if there is a selection
startRow = this._terminal.selectionManager.select... | identifier_body |
SearchHelper.ts | /**
* Copyright (c) 2017 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ISearchHelper, ISearchAddonTerminal } from './Interfaces';
interface ISearchResult {
term: string;
col: number;
row: number;
}
/**
* A class that knows how to search the terminal and how to display the results.
... |
let result: ISearchResult;
let startRow = this._terminal.buffer.ydisp;
if (this._terminal.selectionManager.selectionEnd) {
// Start from the selection end if there is a selection
startRow = this._terminal.selectionManager.selectionEnd[1];
}
// Search from ydisp + 1 to end
for (le... | {
return false;
} | conditional_block |
WHO.js | implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
// attr(... | doc, url) {
if (url.includes("/handle/") && text(doc, 'div.item-summary-view-metadata')) {
var type = attr(doc, 'meta[name="DC.type"]', 'content');
//Z.debug(type);
if (type && type.includes("articles")) {
return "journalArticle";
}
if (type && (type.includes("Book") || type.includes("Publications"))) {
... | etectWeb( | identifier_name |
WHO.js | implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
// attr(... |
return found ? items : false;
}
function doWeb(doc, url) {
if (detectWeb(doc, url) == "multiple") {
Zotero.selectItems(getSearchResults(doc, false), function (items) {
if (!items) {
return true;
}
var articles = [];
for (var i in items) {
articles.push(i);
}
ZU.processDocuments(articles... |
let href = rows[i].href;
var title = rows[i].textContent;
if (!href || !title) continue;
if (checkOnly) return true;
found = true;
items[href] = title;
}
| conditional_block |
WHO.js | the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
// a... | }
}
item.complete();
});
translator.getTranslatorObject(function(trans) {
trans.itemType = type;
trans.doWeb(doc, url);
});
}
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "http://apps.who.int/iris/handle/10665/70863?locale=ar",
"items": [
{
"itemType": "report",... | item.extra += "\nnumber-of-pages: " + numPages[1];
}
delete item.abstractNote; | random_line_split |
WHO.js | implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
// attr(... |
function getSearchResults(doc, checkOnly) {
var items = {};
var found = false;
var rows = doc.querySelectorAll('h4.artifact-title>a');
for (let i=0; i<rows.length; i++) {
let href = rows[i].href;
var title = rows[i].textContent;
if (!href || !title) continue;
if (checkOnly) return true;
found = true;
... |
if (url.includes("/handle/") && text(doc, 'div.item-summary-view-metadata')) {
var type = attr(doc, 'meta[name="DC.type"]', 'content');
//Z.debug(type);
if (type && type.includes("articles")) {
return "journalArticle";
}
if (type && (type.includes("Book") || type.includes("Publications"))) {
return "b... | identifier_body |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2014 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | # Ajout des éditeurs
self.importeur.interpreteur.ajouter_editeur(
editeurs.diledit.EdtDiledit)
@property
def zones(self):
"""Retourne toutes les zones des diligences (actives)."""
cles = [cle + "_" for cle in self.diligences.keys()]
zones = []
for... | random_line_split | |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2014 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | ime une diligence."""
if cle not in self.diligences:
raise ValueError("la diligence {} n'existe pas".format(
repr(cle)))
self.diligences.pop(cle).detruire()
| ):
"""Suppr | identifier_name |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2014 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... |
def creer_diligence(self, cle):
"""Crée une diligence."""
if cle in self.diligences:
raise ValueError("la diligence {} existe déjà".format(
repr(cle)))
diligence = DiligenceMaudite(cle)
self.ajouter_diligence(diligence)
return diligence
... | with(c) for c in cles):
zones.append(zone)
return zones | conditional_block |
__init__.py | # -*-coding:Utf-8 -*
# Copyright (c) 2014 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | nce(self, cle):
"""Crée une diligence."""
if cle in self.diligences:
raise ValueError("la diligence {} existe déjà".format(
repr(cle)))
diligence = DiligenceMaudite(cle)
self.ajouter_diligence(diligence)
return diligence
def ajouter_diligence... | zones des diligences (actives)."""
cles = [cle + "_" for cle in self.diligences.keys()]
zones = []
for zone in importeur.salle.zones.values():
if any(zone.cle.startswith(c) for c in cles):
zones.append(zone)
return zones
def creer_dilige | identifier_body |
radio.rs | use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Vec2;
use crate::{Printer, With};
use std::cell::RefCell;
use std::rc::Rc;
struct SharedState<T> {
selection: usize,
values:... | else {
printer.with_color(ColorStyle::secondary(), |printer| {
self.draw_internal(printer)
});
}
}
fn on_event(&mut self, event: Event) -> EventResult {
if !self.enabled {
return EventResult::Ignored;
}
match event {
... | {
printer.with_selection(printer.focused, |printer| {
self.draw_internal(printer)
});
} | conditional_block |
radio.rs | use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Vec2;
use crate::{Printer, With};
use std::cell::RefCell;
use std::rc::Rc;
struct SharedState<T> {
selection: usize,
values:... | ///
pub struct RadioButton<T> {
state: Rc<RefCell<SharedState<T>>>,
id: usize,
enabled: bool,
label: String,
}
impl<T: 'static> RadioButton<T> {
impl_enabled!(self.enabled);
fn new(
state: Rc<RefCell<SharedState<T>>>,
id: usize,
label: String,
) -> Self {
Ra... | /// time.
///
/// `RadioButton`s are not created directly, but through
/// [`RadioGroup::button`]. | random_line_split |
radio.rs | use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Vec2;
use crate::{Printer, With};
use std::cell::RefCell;
use std::rc::Rc;
struct SharedState<T> {
selection: usize,
values:... |
/// Returns `true` if this button is selected.
pub fn is_selected(&self) -> bool {
self.state.borrow().selection == self.id
}
/// Selects this button, un-selecting any other in the same group.
pub fn select(&mut self) -> EventResult {
let mut state = self.state.borrow_mut();
... | {
RadioButton {
state,
id,
enabled: true,
label,
}
} | identifier_body |
radio.rs | use crate::direction::Direction;
use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent};
use crate::theme::ColorStyle;
use crate::view::View;
use crate::Cursive;
use crate::Vec2;
use crate::{Printer, With};
use std::cell::RefCell;
use std::rc::Rc;
struct SharedState<T> {
selection: usize,
values:... | (&self) -> Rc<T> {
Rc::clone(&self.values[self.selection])
}
}
/// Group to coordinate multiple radio buttons.
///
/// A `RadioGroup` is used to create and manage [`RadioButton`]s.
///
/// A `RadioGroup` can be cloned; it will keep pointing to the same group.
#[derive(Clone)]
pub struct RadioGroup<T> {
... | selection | identifier_name |
momentum_indicators.rs | extern crate tars;
use tars::momentum_indicators::rsi::rsi;
use tars::helpers::round_array;
// Some randomly generated data to test against TA-Lib (see generate_data.py & correct_values.py) | const OPEN: &[f64] = &[1984.03, 1959.83, 2041.42, 2019.04, 1969.53, 2082.75, 2209.52, 2200.9,
2364.04, 2543.32, 2423.95, 2483.28, 2604.88, 2393.81, 2231.27, 2420.82,
2544.0, 2766.67, 2919.62, 2763.25];
const HIGH: &[f64] = &[2174.72, 2129.49, 2158.92, 2050.2, 2042.12, 2151.... | random_line_split | |
momentum_indicators.rs | extern crate tars;
use tars::momentum_indicators::rsi::rsi;
use tars::helpers::round_array;
// Some randomly generated data to test against TA-Lib (see generate_data.py & correct_values.py)
const OPEN: &[f64] = &[1984.03, 1959.83, 2041.42, 2019.04, 1969.53, 2082.75, 2209.52, 2200.9,
2364.04, 25... | {
let mut result = rsi(CLOSE, 6).unwrap();
let expected = &[79.9771, 86.5336, 90.5949, 73.0035, 75.8056, 80.7258, 56.706, 44.4766,
57.3488, 63.879, 72.8847, 77.5072, 64.1009, 70.3536];
round_array(result.as_mut(), 4);
assert_eq!(result, expected);
} | identifier_body | |
momentum_indicators.rs | extern crate tars;
use tars::momentum_indicators::rsi::rsi;
use tars::helpers::round_array;
// Some randomly generated data to test against TA-Lib (see generate_data.py & correct_values.py)
const OPEN: &[f64] = &[1984.03, 1959.83, 2041.42, 2019.04, 1969.53, 2082.75, 2209.52, 2200.9,
2364.04, 25... | () {
let mut result = rsi(CLOSE, 6).unwrap();
let expected = &[79.9771, 86.5336, 90.5949, 73.0035, 75.8056, 80.7258, 56.706, 44.4766,
57.3488, 63.879, 72.8847, 77.5072, 64.1009, 70.3536];
round_array(result.as_mut(), 4);
assert_eq!(result, expected);
}
| rsi_works | identifier_name |
File.tsx | import React from 'react';
import { connect, DispatchProp } from 'react-redux';
import Base from './Base';
import filesize from 'filesize';
import config from '@shared/project.config';
import { downloadFile, previewFile } from '@shared/redux/actions/file';
import type { MessageProps } from '@shared/components/message/M... |
handleDownload() {
const data = this.props.info.data!;
this.props.dispatch(downloadFile(data.fileuuid));
}
getContent() {
const info = this.props.info;
const data = info.data!;
return (
<div className="bubble">
<div className="file-info">
<div
className=... | {
const data = this.props.info.data!;
this.props.dispatch(
previewFile(data.fileuuid, {
WebviewComponent: Webview,
})
);
} | identifier_body |
File.tsx | import React from 'react';
import { connect, DispatchProp } from 'react-redux';
import Base from './Base';
import filesize from 'filesize';
import config from '@shared/project.config';
import { downloadFile, previewFile } from '@shared/redux/actions/file';
import type { MessageProps } from '@shared/components/message/M... | () {
const data = this.props.info.data!;
this.props.dispatch(
previewFile(data.fileuuid, {
WebviewComponent: Webview,
})
);
}
handleDownload() {
const data = this.props.info.data!;
this.props.dispatch(downloadFile(data.fileuuid));
}
getContent() {
const info = this.... | handlePreview | identifier_name |
File.tsx | import React from 'react';
import { connect, DispatchProp } from 'react-redux';
import Base from './Base';
import filesize from 'filesize';
import config from '@shared/project.config';
import { downloadFile, previewFile } from '@shared/redux/actions/file';
import type { MessageProps } from '@shared/components/message/M... | <div className="file-progress">
<div style={{ width: data.progress * 100 + '%' }} />
</div>
) : (
<div className="file-action">
{data.can_preview ? (
<button onClick={() => this.handlePreview()}>
<i className="iconfont">... | random_line_split | |
watchlist.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
python pwb.py watchlist [-all | -new]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
pr... |
if all:
refresh_all(sysop=sysop)
elif new:
refresh_new(sysop=sysop)
else:
site = pywikibot.Site()
watchlist = refresh(site, sysop=sysop)
pywikibot.output(u'%i pages in the watchlist.' % len(watchlist))
for page in watchlist:
try:
p... | sysop = True | conditional_block |
watchlist.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
python pwb.py watchlist [-all | -new]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
pr... | elif new:
refresh_new(sysop=sysop)
else:
site = pywikibot.Site()
watchlist = refresh(site, sysop=sysop)
pywikibot.output(u'%i pages in the watchlist.' % len(watchlist))
for page in watchlist:
try:
pywikibot.stdout(page.title())
exce... | """
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: list of unicode
"""
all = False
new = False
sysop = False
for arg in pywikibot.handle_args(args):
if arg in ('-all', '-update'):
... | identifier_body |
watchlist.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
python pwb.py watchlist [-all | -new]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
pr... | (sysop=False):
"""Load watchlists of all wikis for accounts set in user-config.py."""
pywikibot.output(
'Downloading all watchlists for your accounts in user-config.py')
for family in config.usernames:
for lang in config.usernames[family]:
site = pywikibot.Site(lang, family)
... | refresh_new | identifier_name |
watchlist.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
| -all - Reloads watchlists for all wikis where a watchlist is already
present
-new - Load watchlists for all wikis where accounts is setting in
user-config.py
"""
#
# (C) Daniel Herding, 2005
# (C) Pywikibot team, 2005-2016
#
# Distributed under the terms of the MIT license.
#
from ... | python pwb.py watchlist [-all | -new]
Command line options: | random_line_split |
archive_media.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | content_type, rendition_spec, url_for_media)
doc['renditions'] = renditions
doc['mimetype'] = content_type
doc['filemeta'] = metadata
if not doc.get('_import', None):
set_original_creato... | if 'media' not in doc or doc['media'] is None:
abort(400, description="No media found")
file, content_type, metadata = self.get_file_from_document(doc)
inserted = [doc['media']]
file_type = content_type.split('/')[0]
try:
update_dates_for... | conditional_block |
archive_media.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | doc[config.VERSION] = 1
doc['versioncreated'] = utcnow()
set_item_expiry({}, doc)
rendition_spec = config.RENDITIONS['picture']
renditions = generate_renditions(file, doc['media'], inserted, file_type,
... | type_av = {'image': 'picture', 'audio': 'audio', 'video': 'video'}
def on_create(self, docs):
""" Create corresponding item on file upload """
for doc in docs:
if 'media' not in doc or doc['media'] is None:
abort(400, description="No media found")
file, con... | identifier_body |
archive_media.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | set_item_expiry({}, doc)
rendition_spec = config.RENDITIONS['picture']
renditions = generate_renditions(file, doc['media'], inserted, file_type,
content_type, rendition_spec, url_for_media)
doc['renditions'... | random_line_split | |
archive_media.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | (self, docs):
""" Create corresponding item on file upload """
for doc in docs:
if 'media' not in doc or doc['media'] is None:
abort(400, description="No media found")
file, content_type, metadata = self.get_file_from_document(doc)
inserted = [doc['m... | on_create | identifier_name |
font_metrics.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/. */
//! Access to font metrics from the style system.
#![deny(missing_docs)]
use Atom;
use app_units::Au;
use contex... | } | pub fn get_metrics_provider_for_product() -> ServoMetricsProvider {
ServoMetricsProvider | random_line_split |
font_metrics.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/. */
//! Access to font metrics from the style system.
#![deny(missing_docs)]
use Atom;
use app_units::Au;
use contex... | (&self, _font: &Font, _font_size: Au, _wm: WritingMode,
_in_media_query: bool, _device: &Device) -> FontMetricsQueryResult {
FontMetricsQueryResult::NotAvailable
}
/// Get default size of a given language and generic family
fn get_size(&self, font_name: &Atom, font_family: u8) -> Au;
... | query | identifier_name |
example_pb2.py | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/example/example.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf imp... |
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\026org.tensorflow.exampleB\rExampleProtosP\001\370\001\001'))
try:
# THESE ELEMENTS WILL BE DEPRECATED.
# Please use the generated *_pb2_grpc.py files instead.
import grpc
from grpc.framework.comm... | __module__ = 'tensorflow.core.example.example_pb2'
# @@protoc_insertion_point(class_scope:tensorflow.SequenceExample)
))
_sym_db.RegisterMessage(SequenceExample)
| random_line_split |
105c1c44ff70_login_is_not_nullabl.py | """login is not nullable
Revision ID: 105c1c44ff70
Revises: 2003c675a267
Create Date: 2013-12-09 10:52:50.646000
"""
# revision identifiers, used by Alembic.
revision = '105c1c44ff70'
down_revision = '2003c675a267'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
... |
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
existing_type=mysql.VARCHAR(length=50),
nullable=True)
### end Alembic commands ###
| op.alter_column('labmanager_users', 'login',
existing_type=mysql.VARCHAR(length=50),
nullable=False)
### end Alembic commands ###
| identifier_body |
105c1c44ff70_login_is_not_nullabl.py | """login is not nullable
Revision ID: 105c1c44ff70
Revises: 2003c675a267
Create Date: 2013-12-09 10:52:50.646000
"""
# revision identifiers, used by Alembic.
revision = '105c1c44ff70'
down_revision = '2003c675a267'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
... | ():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
existing_type=mysql.VARCHAR(length=50),
nullable=True)
### end Alembic commands ###
| downgrade | identifier_name |
105c1c44ff70_login_is_not_nullabl.py | """login is not nullable
Revision ID: 105c1c44ff70
Revises: 2003c675a267
Create Date: 2013-12-09 10:52:50.646000
"""
# revision identifiers, used by Alembic.
| revision = '105c1c44ff70'
down_revision = '2003c675a267'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
existing_type=mysql.VAR... | random_line_split | |
gestures.ts | import { Rule, Tree } from '@angular-devkit/schematics';
import { getWorkspace } from '@schematics/angular/utility/config';
import { Schema } from './schema';
import { getProjectFromWorkspace, getProjectMainFile, getAppModulePath, addSymbolToNgModuleMetadata } from '@angular/cdk/schematics';
import { InsertChange } fro... | (options: Schema): Rule {
return (host: Tree, context) => {
context.logger.debug('addHammerJsToMain');
if (!options.gestures) {
return;
}
const workspace = getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const mainFile = getProjectMainFile(project... | addHammerJsToMain | identifier_name |
gestures.ts | import { Rule, Tree } from '@angular-devkit/schematics';
import { getWorkspace } from '@schematics/angular/utility/config';
import { Schema } from './schema';
import { getProjectFromWorkspace, getProjectMainFile, getAppModulePath, addSymbolToNgModuleMetadata } from '@angular/cdk/schematics';
import { InsertChange } fro... |
addImport(host, modulePath, ['LyHammerGestureConfig'], '@alyle/ui');
addImport(host, modulePath, ['HAMMER_GESTURE_CONFIG'], '@angular/platform-browser');
const moduleSource = getTsSourceFile(host, modulePath);
const themeSimbolName = `{ provide: HAMMER_GESTURE_CONFIG, useClass: LyHammerGestureConfig }... |
recorder.insertRight(0, `${hammerjsImportStatement}\n`);
host.commitUpdate(recorder);
| random_line_split |
gestures.ts | import { Rule, Tree } from '@angular-devkit/schematics';
import { getWorkspace } from '@schematics/angular/utility/config';
import { Schema } from './schema';
import { getProjectFromWorkspace, getProjectMainFile, getAppModulePath, addSymbolToNgModuleMetadata } from '@angular/cdk/schematics';
import { InsertChange } fro... |
if (fileContent.includes(hammerjsImportStatement)) {
return console.log(`HammerJS is already imported in the project main file (${mainFile}).`);
}
recorder.insertRight(0, `${hammerjsImportStatement}\n`);
host.commitUpdate(recorder);
addImport(host, modulePath, ['LyHammerGestureConfig'], '@... | {
return (host: Tree, context) => {
context.logger.debug('addHammerJsToMain');
if (!options.gestures) {
return;
}
const workspace = getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const mainFile = getProjectMainFile(project);
const modulePath ... | identifier_body |
gestures.ts | import { Rule, Tree } from '@angular-devkit/schematics';
import { getWorkspace } from '@schematics/angular/utility/config';
import { Schema } from './schema';
import { getProjectFromWorkspace, getProjectMainFile, getAppModulePath, addSymbolToNgModuleMetadata } from '@angular/cdk/schematics';
import { InsertChange } fro... |
const fileContent = buffer.toString('utf8');
if (fileContent.includes(hammerjsImportStatement)) {
return console.log(`HammerJS is already imported in the project main file (${mainFile}).`);
}
recorder.insertRight(0, `${hammerjsImportStatement}\n`);
host.commitUpdate(recorder);
addImp... | {
return console.error(`Could not read the project main file (${mainFile}). Please manually ` +
`import HammerJS in your main TypeScript file.`);
} | conditional_block |
jsGradient.js | jsgradient = {
inputA : '',
inputB : '',
inputC : '',
gradientElement : '',
// Convert a hex color to an RGB array e.g. [r,g,b]
// Accepts the following formats: FFF, FFFFFF, #FFF, #FFFFFF
hexToRgb : function(hex){
var r, g, b, parts;
// Remove the hash if given
hex = hex.replace('#', '');
// ... |
// Generates an array of color values in sequence from 'colorA' to 'colorB' using the specified number of steps
generateGradient : function(colorA, colorB, steps){
var result = [], rInterval, gInterval, bInterval;
colorA = this.hexToRgb(colorA); // [r,g,b]
colorB = this.hexToRgb(colorB); // [r,g,b]
steps ... | }
return number;
}, | random_line_split |
jsGradient.js | jsgradient = {
inputA : '',
inputB : '',
inputC : '',
gradientElement : '',
// Convert a hex color to an RGB array e.g. [r,g,b]
// Accepts the following formats: FFF, FFFFFF, #FFF, #FFFFFF
hexToRgb : function(hex){
var r, g, b, parts;
// Remove the hash if given
hex = hex.replace('#', '');
// ... | ;
result.push( '#'+this.rgbToHex(colorB) );
return result;
},
gradientList : function(colorA, colorB, list){
var list = (typeof list === 'object')? list : document.querySelector(list);
var listItems = list.querySelectorAll('li'),
steps = listItems.length,
colors = jsgradient.generateGradient... | {
// If the first value is lower than the last - increment up otherwise increment down
rVal = (colorA[0] < colorB[0]) ? rVal + Math.round(rStep) : rVal - Math.round(rStep);
gVal = (colorA[1] < colorB[1]) ? gVal + Math.round(gStep) : gVal - Math.round(gStep);
bVal = (colorA[2] < colorB[2]) ? bVal + Math.roun... | conditional_block |
mod.rs | pub mod data_cache;
use std::collections::HashMap;
use std::option::Option;
use self::data_cache::base_data::City;
struct DfaState {
name:String,
path:HashMap<char, DfaState>,
}
impl DfaState {
fn new(n:String) -> DfaState {
DfaState{name:n, path:HashMap::default()}
}
fn add_path(&mut self, c:... | } else {
self.scan_recur(chars, from_idx + 1, from_idx + 1, currect_accepted_idx, &self.start_state, current_accepted, res);
},
Some(cs) => if current_idx + 1 == len {
if cs.is_accepted() {
if !res.contains(&cs.name) {
res.push(cs.name.to_string());
}
self.scan_rec... | }
self.scan_recur(chars, currect_accepted_idx + 1, currect_accepted_idx+1, 0, &self.start_state, &self.start_state, res);
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.