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
filter_dates.py
''' Filter text output by date ranges ''' import os import csv import sys import dateutil.parser import argparse import metadata settings = None def get_settings(): ''' Return command-line settings ''' parser = argparse.ArgumentParser(description='Filter text corpus by date range. Only updates the metadata file.'...
(metadata, start, end): results = list() if start is not None: start = dateutil.parser.parse(start) if end is not None: end = dateutil.parser.parse(end) for row in metadata: try: date = dateutil.parser.parse(row['date']) except ValueError as err: print('No date found in row: {}'.form...
filter_dates
identifier_name
filter_dates.py
''' Filter text output by date ranges ''' import os import csv import sys import dateutil.parser import argparse import metadata settings = None def get_settings(): ''' Return command-line settings ''' parser = argparse.ArgumentParser(description='Filter text corpus by date range. Only updates the metadata file.'...
return results def main(): global settings settings = get_settings() md = metadata.read_csv(settings.input) filtered = filter_dates(md, settings.start, settings.end) metadata.write_csv(settings.output, filtered) if __name__ == '__main__': if sys.version_info < (3,0): print("This script requires Pyt...
try: date = dateutil.parser.parse(row['date']) except ValueError as err: print('No date found in row: {}'.format(row)) else: # if date is None: # continue if (start is None or start <= date) and (end is None or date <= end): results.append(row)
conditional_block
issue-6892.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// option. This file may not be copied, modified, or distributed // except according to those terms. // Ensures that destructors are run for expressions of the form "let _ = e;" // where `e` is a type which requires a destructor. // pretty-expanded FIXME #23616 struct Foo; struct Bar { x: isize } struct Baz(isize); ...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
issue-6892.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self) { unsafe { NUM_DROPS += 1; } } } impl Drop for FooBar { fn drop(&mut self) { unsafe { NUM_DROPS += 1; } } } fn main() { assert_eq!(unsafe { NUM_DROPS }, 0); { let _x = Foo; } assert_eq!(unsafe { NUM_DROPS }, 1); { let _x = Bar { x: 21 }; } assert_eq!(unsafe {...
drop
identifier_name
issue-6892.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
assert_eq!(unsafe { NUM_DROPS }, 11); { let _ = FooBar::_Bar(42); } assert_eq!(unsafe { NUM_DROPS }, 12); }
{ assert_eq!(unsafe { NUM_DROPS }, 0); { let _x = Foo; } assert_eq!(unsafe { NUM_DROPS }, 1); { let _x = Bar { x: 21 }; } assert_eq!(unsafe { NUM_DROPS }, 2); { let _x = Baz(21); } assert_eq!(unsafe { NUM_DROPS }, 3); { let _x = FooBar::_Foo(Foo); } assert_eq!(unsafe { NUM_DROPS }, 5...
identifier_body
template.ts
.template { /** * Detect repeating patterns of subgraphs. * Assign templateId to each subgraph if it belongs to a template. * Returns clusters of similar subgraphs . * * @param graph * @param verifyTemplate whether to run the template verification algorithm * @return a dict (template id => Array of node names) ...
// check node let similar = isSimilarNode(g1.node(cur.n1), g2.node(cur.n2)); if (!similar) { return false; } // check if have same # of successors then sort and push let succ1 = g1.successors(cur.n1), succ2 = g2.successors(cur.n2); if (succ1.length !== succ2.length) { /* tsli...
let cur = stack.pop();
random_line_split
template.ts
.template { /** * Detect repeating patterns of subgraphs. * Assign templateId to each subgraph if it belongs to a template. * Returns clusters of similar subgraphs . * * @param graph * @param verifyTemplate whether to run the template verification algorithm * @return a dict (template id => Array of node names) ...
// filter nn metanode with only one member .filter(function(pair) { return pair[1].nodes.length > 1; }) .sortBy(function(pair) { // sort by depth // (all members in the same nnGroup has equal depth) return pair[1].nodes[0...
{ /** a dict from metanode.signature() => Array of tf.graph.Groups */ let hashDict = _(h.getNodeMap()).reduce( (hash, node: OpNode|Metanode, name) => { if (node.type !== NodeType.META) { return hash; } let levelOfMetaNode = name.split("/").length - 1; let signature = getSignature(node)...
identifier_body
template.ts
{ /** * Detect repeating patterns of subgraphs. * Assign templateId to each subgraph if it belongs to a template. * Returns clusters of similar subgraphs . * * @param graph * @param verifyTemplate whether to run the template verification algorithm * @return a dict (template id => Array of node names) */ expor...
/* tslint:enable */ if (!visited1[sub1]) { // implied && !visited2[sub2] visited1[sub1] = visited2[sub2] = true; stack.push({n1: n1, n2: n2}); } return false; } // check if have same # of sources then sort and push let sources1 = g1.sources(); let sources2 = g2.sources(); if (so...
{ console.warn("different visit pattern", "[" + g1prefix + "]", sub1, "[" + g2prefix + "]", sub2); return true; }
conditional_block
template.ts
.template { /** * Detect repeating patterns of subgraphs. * Assign templateId to each subgraph if it belongs to a template. * Returns clusters of similar subgraphs . * * @param graph * @param verifyTemplate whether to run the template verification algorithm * @return a dict (template id => Array of node names) ...
(h: hierarchy.Hierarchy) { /** a dict from metanode.signature() => Array of tf.graph.Groups */ let hashDict = _(h.getNodeMap()).reduce( (hash, node: OpNode|Metanode, name) => { if (node.type !== NodeType.META) { return hash; } let levelOfMetaNode = name.split("/").length - 1; let signa...
clusterSimilarSubgraphs
identifier_name
test_metrics_fluster.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::thread::sleep; use std::time::Duration; use engine_rocks::raw::{DBOptions, TitanDBOptions}; use tempfile::Builder; use engine_rocks::util::{self as rocks_util, RocksCFOptions}; use engine_rocks::{RocksColumnFamilyOptions...
let rtime = Duration::from_millis(300); sleep(rtime); metrics_flusher.stop(); }
{ error!("failed to start metrics flusher, error = {:?}", e); }
conditional_block
test_metrics_fluster.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::thread::sleep; use std::time::Duration; use engine_rocks::raw::{DBOptions, TitanDBOptions}; use tempfile::Builder; use engine_rocks::util::{self as rocks_util, RocksCFOptions}; use engine_rocks::{RocksColumnFamilyOptions...
RocksColumnFamilyOptions::new(), )]; let raft_engine = rocks_util::new_engine_opt( raft_path.to_str().unwrap(), RocksDBOptions::from_raw(DBOptions::new()), cfs_opts, ) .unwrap(); let engines = Engines::new(engine, raft_engine); let mut metrics_flusher = MetricsFl...
{ let path = Builder::new() .prefix("_test_metrics_flusher") .tempdir() .unwrap(); let raft_path = path.path().join(Path::new("raft")); let mut db_opt = DBOptions::new(); db_opt.set_titandb_options(&TitanDBOptions::new()); let db_opt = RocksDBOptions::from_raw(db_opt); le...
identifier_body
test_metrics_fluster.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::thread::sleep; use std::time::Duration; use engine_rocks::raw::{DBOptions, TitanDBOptions}; use tempfile::Builder; use engine_rocks::util::{self as rocks_util, RocksCFOptions}; use engine_rocks::{RocksColumnFamilyOptions...
() { let path = Builder::new() .prefix("_test_metrics_flusher") .tempdir() .unwrap(); let raft_path = path.path().join(Path::new("raft")); let mut db_opt = DBOptions::new(); db_opt.set_titandb_options(&TitanDBOptions::new()); let db_opt = RocksDBOptions::from_raw(db_opt); ...
test_metrics_flusher
identifier_name
test_metrics_fluster.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use std::path::Path; use std::thread::sleep; use std::time::Duration; use engine_rocks::raw::{DBOptions, TitanDBOptions}; use tempfile::Builder; use engine_rocks::util::{self as rocks_util, RocksCFOptions}; use engine_rocks::{RocksColumnFamilyOptions...
) .unwrap(); let engines = Engines::new(engine, raft_engine); let mut metrics_flusher = MetricsFlusher::new(engines); metrics_flusher.set_flush_interval(Duration::from_millis(100)); if let Err(e) = metrics_flusher.start() { error!("failed to start metrics flusher, error = {:?}", e); ...
)]; let raft_engine = rocks_util::new_engine_opt( raft_path.to_str().unwrap(), RocksDBOptions::from_raw(DBOptions::new()), cfs_opts,
random_line_split
eight_queens.py
"""Backtracking example: 8-queens problem.""" if __name__ == "__main__": import sys import os.path as op sys.path.append(op.abspath(op.join('..', 'packages'))) from pycog.statemachine import * from pycog.exceptions import * from pycog.backtrack import * from pycog.utility.diagram import diagram # Strateg...
queens: Set of (row, col) coordinates, each being the position of one of the eight queens. """ def __init__(self): super().__init__(initial='init') self.queens = set() # Add states for each square for row in range(8): for col in range(8): ...
""" Solve the 8-queens problem using backtracking. State Strategy: The state names are 'init', 'final' and the coordinates (row, col) on the chessboard. There is no state data, the names contain all the information we need. Transition Strategy: 'init' transitions to the fi...
identifier_body
eight_queens.py
"""Backtracking example: 8-queens problem.""" if __name__ == "__main__": import sys import os.path as op sys.path.append(op.abspath(op.join('..', 'packages'))) from pycog.statemachine import * from pycog.exceptions import * from pycog.backtrack import * from pycog.utility.diagram import diagram # Strateg...
# Add transitions for row in range(8): # Transitions from 'init' and to 'final'. if row < 4: self.add_transition('init', (row, 0)) self.add_transition((row, 7), 'final') for col in range(7): for next_row in range(8): ...
for col in range(8): self.add_state((row, col), activity=EightQueens.place_queen)
conditional_block
eight_queens.py
"""Backtracking example: 8-queens problem.""" if __name__ == "__main__": import sys import os.path as op sys.path.append(op.abspath(op.join('..', 'packages'))) from pycog.statemachine import * from pycog.exceptions import * from pycog.backtrack import * from pycog.utility.diagram import diagram # Strateg...
(self): super().__init__(initial='init') self.queens = set() # Add states for each square for row in range(8): for col in range(8): self.add_state((row, col), activity=EightQueens.place_queen) # Add transitions for row in range(8): ...
__init__
identifier_name
eight_queens.py
"""Backtracking example: 8-queens problem.""" if __name__ == "__main__": import sys import os.path as op sys.path.append(op.abspath(op.join('..', 'packages'))) from pycog.statemachine import * from pycog.exceptions import * from pycog.backtrack import * from pycog.utility.diagram import diagram # Strateg...
if (next_row, col) in fsm.queens: return False # check the two diagonals so far, from (next_row, next_col) diag_len = min(next_row, next_col) for step in range(diag_len): if (next_row - step - 1, next_col - step - 1) in fsm.queens: return False diag_len = min(7 ...
# check the row for col in range(next_col):
random_line_split
tooltip.ts
import * as R from 'ramda'; import { IUSerInterfaceTooltip, ITableHeaderTooltips, ITableStaticTooltips, IVirtualizedDerivedData, DataTooltips } from 'dash-table/components/Table/props'; import {ifColumnId, ifRowIndex, ifFilter} from 'dash-table/conditional'; import { ConditionalTooltip, Too...
if (conditionalTooltips) { return conditionalTooltips; } let tooltip: Tooltip | null | undefined; if (header) { const headerTooltip = tooltip_header?.[id]; tooltip = Array.isArray(headerTooltip) ? headerTooltip?.[row] : headerTooltip; } else { ...
)) ); }, tooltip_conditional);
random_line_split
tooltip.ts
import * as R from 'ramda'; import { IUSerInterfaceTooltip, ITableHeaderTooltips, ITableStaticTooltips, IVirtualizedDerivedData, DataTooltips } from 'dash-table/components/Table/props'; import {ifColumnId, ifRowIndex, ifFilter} from 'dash-table/conditional'; import { ConditionalTooltip, Too...
function getDuration(duration: number | null | undefined, defaultTo: number) { return typeof duration === 'number' || duration === null ? convertDuration(duration) : defaultTo; } export default memoizeOne( ( currentTooltip: IUSerInterfaceTooltip, tooltip_data: DataTooltips, ...
{ return typeof delay === 'number' || delay === null ? convertDelay(delay) : defaultTo; }
identifier_body
tooltip.ts
import * as R from 'ramda'; import { IUSerInterfaceTooltip, ITableHeaderTooltips, ITableStaticTooltips, IVirtualizedDerivedData, DataTooltips } from 'dash-table/components/Table/props'; import {ifColumnId, ifRowIndex, ifFilter} from 'dash-table/conditional'; import { ConditionalTooltip, Too...
( currentTooltip: IUSerInterfaceTooltip, tooltip_data: DataTooltips, tooltip_header: ITableHeaderTooltips, tooltip_conditional: ConditionalTooltip[], tooltip_static: ITableStaticTooltips, virtualized: IVirtualizedDerivedData ) { if (!currentTooltip) { return undefined; } con...
getSelectedTooltip
identifier_name
tooltip.ts
import * as R from 'ramda'; import { IUSerInterfaceTooltip, ITableHeaderTooltips, ITableStaticTooltips, IVirtualizedDerivedData, DataTooltips } from 'dash-table/components/Table/props'; import {ifColumnId, ifRowIndex, ifFilter} from 'dash-table/conditional'; import { ConditionalTooltip, Too...
const {header, id, row} = currentTooltip; if (id === undefined || row === undefined) { return undefined; } const conditionalTooltips = header ? undefined : R.findLast(tt => { return ( !tt.if || (ifColumnId(tt.if, id) && ...
{ return undefined; }
conditional_block
closing-spawned-feed.rs
use futures::{StreamExt, TryStreamExt}; use futures_timer::Delay; use log::error; use reql::r; use serde_json::Value; use std::time::Duration; // We are using `tokio` here as an example but you can use this crate // with any runtime #[tokio::main] async fn main() -> reql::Result<()>
let mut query = r.db("rethinkdb").table("jobs").changes(()).run(conn); // Execute the query and handle the result while let Some(change) = query.next().await { match change { // We are going to continue printing jobs until the feed is closed Ok(change...
{ // Initialise the logger if you need to debug this crate env_logger::init(); // Connect to create a RethinkDB session let session = r.connect(()).await?; // Manually get a connection from the session // Usually, this is not necessary (see other examples) but in this // case we need a han...
identifier_body
closing-spawned-feed.rs
use futures::{StreamExt, TryStreamExt}; use futures_timer::Delay; use log::error; use reql::r; use serde_json::Value; use std::time::Duration; // We are using `tokio` here as an example but you can use this crate // with any runtime #[tokio::main] async fn main() -> reql::Result<()> { // Initialise the logger if y...
let feed_handle = tokio::spawn(async { // Create the query you want to run // The query returns a `Stream` of responses from RethinkDB let mut query = r.db("rethinkdb").table("jobs").changes(()).run(conn); // Execute the query and handle the result while let Some(change) = q...
// Spawn the changefeed to run it in the background
random_line_split
closing-spawned-feed.rs
use futures::{StreamExt, TryStreamExt}; use futures_timer::Delay; use log::error; use reql::r; use serde_json::Value; use std::time::Duration; // We are using `tokio` here as an example but you can use this crate // with any runtime #[tokio::main] async fn
() -> reql::Result<()> { // Initialise the logger if you need to debug this crate env_logger::init(); // Connect to create a RethinkDB session let session = r.connect(()).await?; // Manually get a connection from the session // Usually, this is not necessary (see other examples) but in this ...
main
identifier_name
tasks.py
import logging import traceback import sys from celery import Celery from .callbacks import STATUS_LOADING_DATA from .config import get_engine, _set_connection_string from .loader import FDPLoader from .callbacks import do_request, STATUS_INITIALIZING, STATUS_FAIL, STATUS_DONE app = Celery('fdp_loader') app.config_f...
raise RuntimeError(send_progress.error)
conditional_block
tasks.py
import logging import traceback import sys from celery import Celery from .callbacks import STATUS_LOADING_DATA from .config import get_engine, _set_connection_string from .loader import FDPLoader from .callbacks import do_request, STATUS_INITIALIZING, STATUS_FAIL, STATUS_DONE app = Celery('fdp_loader') app.config_f...
(object): def __init__(self, callback, package): self.count = 0 self.callback = callback self.package = package self.error = None def __call__(self, status=STATUS_LOADING_DATA, count=None, data=None, error=None): if error is not None: self.error = error ...
ProgressSender
identifier_name
tasks.py
import logging import traceback import sys from celery import Celery from .callbacks import STATUS_LOADING_DATA from .config import get_engine, _set_connection_string from .loader import FDPLoader from .callbacks import do_request, STATUS_INITIALIZING, STATUS_FAIL, STATUS_DONE app = Celery('fdp_loader') app.config_f...
def __call__(self, status=STATUS_LOADING_DATA, count=None, data=None, error=None): if error is not None: self.error = error if count is None: count = self.count else: self.count = count logging.info('CALLBACK: %s %s (%s / %s)', ...
self.count = 0 self.callback = callback self.package = package self.error = None
identifier_body
tasks.py
import logging import traceback import sys from celery import Celery from .callbacks import STATUS_LOADING_DATA from .config import get_engine, _set_connection_string from .loader import FDPLoader from .callbacks import do_request, STATUS_INITIALIZING, STATUS_FAIL, STATUS_DONE app = Celery('fdp_loader') app.config_f...
def load_fdp_task(package, callback, connection_string=None): send_progress = ProgressSender(callback, package) if connection_string is not None: _set_connection_string(connection_string) try: logging.info("Starting to load %s" % package) send_progress(status=STATUS_INITIALIZING) ...
do_request(self.callback, self.package, status, progress=count, error=error, data=data) @app.task
random_line_split
l10n_ve_dpt.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
"""States Parishes""" _name = 'res.country.state.municipality.parish' _description="Municipality parishes" municipality_id = fields.Many2one('res.country.state.municipality', 'Municipality', help='Name of the Municipality to which the parish belongs') name = fields.Char('Parish', required=True, help='P...
identifier_body
l10n_ve_dpt.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE...
# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as
random_line_split
l10n_ve_dpt.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(models.Model): """ Add Municipalities reference in State """ _name = 'res.country.state' _inherit = 'res.country.state' _description="Country states" municipality_id = fields.One2many('res.country.state.municipality', 'state_id', 'Municipalities in this state') class StateMunicipality(models.Mod...
CountryState
identifier_name
basic.rs
#[cfg(all(feature = "std_rng", feature = "default_dictionary"))] use petname::petname; use petname::Petnames; use rand::rngs::mock::StepRng; #[test] #[cfg(feature = "default_dictionary")] fn default_petnames_has_adjectives() { let petnames = Petnames::default(); assert_ne!(petnames.adjectives.len(), 0); } #[t...
assert_eq!(Vec::<String>::new(), names); } #[test] fn petnames_iter_non_repeating_yields_nothing_when_no_word_lists_are_given() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("a1 a2", "b1 b2", "c1 c2"); let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 0, ".").collect();...
let petnames = Petnames::init("a1 a2", "", "c1 c2"); let names: Vec<String> = petnames.iter_non_repeating(&mut rng, 3, ".").collect();
random_line_split
basic.rs
#[cfg(all(feature = "std_rng", feature = "default_dictionary"))] use petname::petname; use petname::Petnames; use rand::rngs::mock::StepRng; #[test] #[cfg(feature = "default_dictionary")] fn default_petnames_has_adjectives() { let petnames = Petnames::default(); assert_ne!(petnames.adjectives.len(), 0); } #[t...
#[test] fn petnames_iter_yields_names() { let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("foo", "bar", "baz"); let names = petnames.iter(&mut rng, 3, "."); // Definintely an Iterator... let mut iter: Box<dyn Iterator<Item = _>> = Box::new(names); assert_eq!(Some("bar.foo.baz"....
{ let mut rng = StepRng::new(0, 1); let petnames = Petnames::init("a b", "c d e", "f g h i"); let names = petnames.iter(&mut rng, 3, "."); assert_eq!(24u128, names.cardinality()); }
identifier_body
basic.rs
#[cfg(all(feature = "std_rng", feature = "default_dictionary"))] use petname::petname; use petname::Petnames; use rand::rngs::mock::StepRng; #[test] #[cfg(feature = "default_dictionary")] fn default_petnames_has_adjectives() { let petnames = Petnames::default(); assert_ne!(petnames.adjectives.len(), 0); } #[t...
() { let petnames = Petnames { adjectives: vec!["adjective"], adverbs: vec!["adverb"], names: vec!["name"], }; assert_eq!( petnames.generate(&mut StepRng::new(0, 1), 3, "-"), "adverb-adjective-name" ); } #[test] #[cfg(all(feature = "std_rng", feature = "default_d...
generate_uses_adverb_adjective_name
identifier_name
test_readers.py
import unittest from exporters.readers.base_reader import BaseReader from exporters.readers.random_reader import RandomReader from .utils import meta class BaseReaderTest(unittest.TestCase): def setUp(self): self.reader = BaseReader({}, meta()) def test_get_next_batch_not_implemented(self): ...
self.assertEqual(total_items, self.options['reader']['options']['number_of_items']) def test_set_last_position_none(self): self.reader.set_last_position({'last_read': 123}) self.assertEqual({'last_read': 123}, self.reader.last_position)
batch = list(self.reader.get_next_batch()) total_items += len(batch)
conditional_block
test_readers.py
import unittest from exporters.readers.base_reader import BaseReader from exporters.readers.random_reader import RandomReader from .utils import meta class BaseReaderTest(unittest.TestCase): def setUp(self): self.reader = BaseReader({}, meta()) def test_get_next_batch_not_implemented(self): ...
self.reader.set_last_position({'last_read': 123}) self.assertEqual({'last_read': 123}, self.reader.last_position)
def test_set_last_position_none(self):
random_line_split
test_readers.py
import unittest from exporters.readers.base_reader import BaseReader from exporters.readers.random_reader import RandomReader from .utils import meta class BaseReaderTest(unittest.TestCase): def setUp(self):
def test_get_next_batch_not_implemented(self): with self.assertRaises(NotImplementedError): self.reader.get_next_batch() def test_set_last_position(self): self.reader.set_last_position(dict(position=5)) self.assertEqual(self.reader.last_position, dict(position=5)) class ...
self.reader = BaseReader({}, meta())
identifier_body
test_readers.py
import unittest from exporters.readers.base_reader import BaseReader from exporters.readers.random_reader import RandomReader from .utils import meta class
(unittest.TestCase): def setUp(self): self.reader = BaseReader({}, meta()) def test_get_next_batch_not_implemented(self): with self.assertRaises(NotImplementedError): self.reader.get_next_batch() def test_set_last_position(self): self.reader.set_last_position(dict(posi...
BaseReaderTest
identifier_name
sudoku.rs
u8, start_color: u8) -> bool { if start_color < 10u8 { // colors not yet used let mut avail = ~Colors::new(start_color); // drop colors already in use in neighbourhood self.drop_colors(avail, row, col); // find first remaining color that is availabl...
main
identifier_name
sudoku.rs
, ..9], ..9]) -> Sudoku { let mut g = do vec::from_fn(9u) |i| { do vec::from_fn(9u) |j| { vec[i][j] } }; return Sudoku::new(g) } pub fn equal(&self, other: &Sudoku) -> bool { for u8::range(0u8, 9u8) |row| { for u8::range(0u8, 9u8) |col| { ...
else { fail!("Invalid sudoku file"); } } return Sudoku::new(g) } pub fn write(&self, writer: @io::Writer) { for u8::range(0u8, 9u8) |row| { writer.write_str(fmt!("%u", self.grid[row][0] as uint)); for u8::range(1u8, 9u8) |...
{ let row = uint::from_str(comps[0]).get() as u8; let col = uint::from_str(comps[1]).get() as u8; g[row][col] = uint::from_str(comps[2]).get() as u8; }
conditional_block
sudoku.rs
, ..9], ..9]) -> Sudoku { let mut g = do vec::from_fn(9u) |i| { do vec::from_fn(9u) |j| { vec[i][j] } }; return Sudoku::new(g) } pub fn equal(&self, other: &Sudoku) -> bool { for u8::range(0u8, 9u8) |row| { for u8::range(0u8, 9u8) |col| { ...
} } // Stores available colors as simple bitfield, bit 0 is always unset struct Colors(u16); static heads: u16 = (1u16 << 10) - 1; /* bits 9..0 */ impl Colors { fn new(start_color: u8) -> Colors { // Sets bits 9..start_color let tails = !0u16 << start_color; return Colors(heads & tai...
{ for u8::range(0u8, 9u8) |idx| { avail.remove(self.grid[idx][col]); /* check same column fields */ avail.remove(self.grid[row][idx]); /* check same row fields */ } // check same block fields let row0 = (row / 3u8) * 3u8; let col0 = (col / 3u8) * 3u8; ...
identifier_body
sudoku.rs
, ..9], ..9]) -> Sudoku { let mut g = do vec::from_fn(9u) |i| { do vec::from_fn(9u) |j| { vec[i][j] } }; return Sudoku::new(g) } pub fn equal(&self, other: &Sudoku) -> bool { for u8::range(0u8, 9u8) |row| { for u8::range(0u8, 9u8) |col| { ...
let val = **self & heads; if (0u16 == val) { return 0u8; } else { unsafe { return cttz16(val as i16) as u8; } } } fn remove(&mut self, color: u8) { if color != 0u8 { let val = **self; let mask =...
fn next(&self) -> u8 {
random_line_split
GofmtBear.py
from coalib.bearlib.abstractions.Linter import linter from coalib.bears.requirements.GoRequirement import GoRequirement @linter(executable='gofmt', use_stdin=True, output_format='corrected', result_message='Formatting can be improved.') class
: """ Suggest better formatting options in Go code. Basic checks like alignment, indentation, and redundant parentheses are provided. This is done using the ``gofmt`` utility. For more information visit <https://golang.org/cmd/gofmt/>. """ LANGUAGES = {'Go'} REQUIREMENTS = {GoRequiremen...
GofmtBear
identifier_name
GofmtBear.py
from coalib.bearlib.abstractions.Linter import linter from coalib.bears.requirements.GoRequirement import GoRequirement @linter(executable='gofmt', use_stdin=True, output_format='corrected', result_message='Formatting can be improved.') class GofmtBear:
""" Suggest better formatting options in Go code. Basic checks like alignment, indentation, and redundant parentheses are provided. This is done using the ``gofmt`` utility. For more information visit <https://golang.org/cmd/gofmt/>. """ LANGUAGES = {'Go'} REQUIREMENTS = {GoRequirement(pack...
identifier_body
GofmtBear.py
from coalib.bearlib.abstractions.Linter import linter from coalib.bears.requirements.GoRequirement import GoRequirement @linter(executable='gofmt', use_stdin=True, output_format='corrected', result_message='Formatting can be improved.') class GofmtBear: """ Suggest better formatting op...
def create_arguments(filename, file, config_file): return ()
@staticmethod
random_line_split
utils.py
import json import click class Echo(object): @staticmethod def info(message, **kwargs): click.echo(click.style(message, fg='green'), **kwargs) @staticmethod def error(message, **kwargs): click.echo(click.style(message, fg='red'), **kwargs) @staticmethod def warn(message, **kw...
return True def json_pretty_dump(obj, fd): json.dump(obj, fd, ensure_ascii=False, indent=4, separators=[',', ':']) vcKey = [604825, 607300, 613847, 615318, 624009, 631856, 635451, 637218, 640529, 643036, 652687, 658008, 662481, 669598, 675545, 685034, 687703, 696444, 702593, 703894, 711191...
return False
conditional_block
utils.py
import json import click class Echo(object): @staticmethod def info(message, **kwargs): click.echo(click.style(message, fg='green'), **kwargs) @staticmethod def error(message, **kwargs): click.echo(click.style(message, fg='red'), **kwargs) @staticmethod def warn(message, **kw...
(dictionary, *args): if not dictionary: return False for key in args: if key not in dictionary: return False return True def json_pretty_dump(obj, fd): json.dump(obj, fd, ensure_ascii=False, indent=4, separators=[',', ':']) vcKey = [604825, 607300, 613847, 615318, 624009, ...
has_keys
identifier_name
utils.py
import json import click
click.echo(click.style(message, fg='green'), **kwargs) @staticmethod def error(message, **kwargs): click.echo(click.style(message, fg='red'), **kwargs) @staticmethod def warn(message, **kwargs): click.echo(click.style(message, fg='red'), **kwargs) def has_keys(dictionary, *ar...
class Echo(object): @staticmethod def info(message, **kwargs):
random_line_split
utils.py
import json import click class Echo(object): @staticmethod def info(message, **kwargs): click.echo(click.style(message, fg='green'), **kwargs) @staticmethod def error(message, **kwargs): click.echo(click.style(message, fg='red'), **kwargs) @staticmethod def warn(message, **kw...
def json_pretty_dump(obj, fd): json.dump(obj, fd, ensure_ascii=False, indent=4, separators=[',', ':']) vcKey = [604825, 607300, 613847, 615318, 624009, 631856, 635451, 637218, 640529, 643036, 652687, 658008, 662481, 669598, 675545, 685034, 687703, 696444, 702593, 703894, 711191, 714166, 720579...
if not dictionary: return False for key in args: if key not in dictionary: return False return True
identifier_body
03. XML Messenger.js
function solve(message) { let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/; let tokens = tagValidator.exec(message); if (!tokens) { console.log("Invalid message format"); return; } let [match, attributes, body] = tokens; let attribute...
attributeTokens = attributeValidator.exec(attributes); } if (sender === '' || recipient === '') { console.log("Missing attributes"); return; } body = body.replace(/\n/g, '</p>\n <p>'); let html = `<article>\n <div>From: <span class="sender">${sender}</span></div>\n`; ...
{ sender = attributeTokens[2]; }
conditional_block
03. XML Messenger.js
function
(message) { let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/; let tokens = tagValidator.exec(message); if (!tokens) { console.log("Invalid message format"); return; } let [match, attributes, body] = tokens; let attributeValidator = /\...
solve
identifier_name
03. XML Messenger.js
function solve(message) { let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/; let tokens = tagValidator.exec(message); if (!tokens) { console.log("Invalid message format"); return; } let [match, attributes, body] = tokens; let attribute...
`<message from="Ivan Ivanov" to="Grace">Not much, just chillin. How about you?</message>` ); */
random_line_split
03. XML Messenger.js
function solve(message)
attributeTokens = attributeValidator.exec(attributes); } if (sender === '' || recipient === '') { console.log("Missing attributes"); return; } body = body.replace(/\n/g, '</p>\n <p>'); let html = `<article>\n <div>From: <span class="sender">${sender}</span></div>\n`; ...
{ let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/; let tokens = tagValidator.exec(message); if (!tokens) { console.log("Invalid message format"); return; } let [match, attributes, body] = tokens; let attributeValidator = /\s+([a-z]+)...
identifier_body
fade-bulleted.js
jQuery(document).ready(function($){ //var timings //var fade_rand var blocked = false; var slide_names = "fade_"+fade_rand+"_slide_"; var current_slide = 0; $(document).oneTime(timings[0],fade_rand+"_timer", function(){ change_slide(null); }); $("#fade_"+fade_rand+" div.fade_bullets_bullets ul li"...
$("#fade_"+fade_rand+" div.fade_bullets_bullets ul li#fade_bullet_"+nextnum).addClass("active"); next.fadeIn(500, function(){ current_slide = nextnum; blocked = false; $(document).oneTime(timings[current_slide],fade_rand+"_timer", function(){ change_slide(null); }); ...
{ blocked = true; if(next_slide != null){ var nextnum = next_slide; } else{ var nextnum = parseInt(current_slide) +1; } next = $("#"+slide_names+nextnum); next_id = next.attr("id"); if(next_slide == null){ if(typeof(next_id) == "undefined"){ next = $("#"+slide_names+...
conditional_block
fade-bulleted.js
jQuery(document).ready(function($){ //var timings //var fade_rand var blocked = false; var slide_names = "fade_"+fade_rand+"_slide_"; var current_slide = 0; $(document).oneTime(timings[0],fade_rand+"_timer", function(){ change_slide(null); }); $("#fade_"+fade_rand+" div.fade_bullets_bullets ul li"...
current.fadeOut(500,function(){ $("#fade_"+fade_rand+" div.fade_bullets_bullets ul li#fade_bullet_"+nextnum).addClass("active"); next.fadeIn(500, function(){ current_slide = nextnum; blocked = false; $(document).oneTime(timings[current_slide],fade_rand+"_timer", function(){ ...
{ if(blocked == false){ blocked = true; if(next_slide != null){ var nextnum = next_slide; } else{ var nextnum = parseInt(current_slide) +1; } next = $("#"+slide_names+nextnum); next_id = next.attr("id"); if(next_slide == null){ if(typeof(next_id) == "undefined"){ ...
identifier_body
fade-bulleted.js
jQuery(document).ready(function($){ //var timings //var fade_rand var blocked = false; var slide_names = "fade_"+fade_rand+"_slide_"; var current_slide = 0; $(document).oneTime(timings[0],fade_rand+"_timer", function(){ change_slide(null); }); $("#fade_"+fade_rand+" div.fade_bullets_bullets ul li"...
(next_slide){ if(blocked == false){ blocked = true; if(next_slide != null){ var nextnum = next_slide; } else{ var nextnum = parseInt(current_slide) +1; } next = $("#"+slide_names+nextnum); next_id = next.attr("id"); if(next_slide == null){ if(typeof(next_id) == "undefin...
change_slide
identifier_name
fade-bulleted.js
jQuery(document).ready(function($){ //var timings //var fade_rand var blocked = false; var slide_names = "fade_"+fade_rand+"_slide_"; var current_slide = 0; $(document).oneTime(timings[0],fade_rand+"_timer", function(){ change_slide(null); }); $("#fade_"+fade_rand+" div.fade_bullets_bullets ul li"...
next = $("#"+slide_names+nextnum); next_id = next.attr("id"); if(next_slide == null){ if(typeof(next_id) == "undefined"){ next = $("#"+slide_names+"0"); nextnum = 0; } } var current = $("#"+slide_names+current_slide); if(current.attr("id") != next.attr("id")){ $("#fade_...
var nextnum = parseInt(current_slide) +1; }
random_line_split
paginationMixin.ts
import { AspectAdvice } from 'dojo-compose/compose'; /** * This mixin provides the ability to view discrete 'pages' of rows. The type is expressed using a class becase, as with * the case of editor and decorator, it is more concise to express a mixture of complex types and function * implementations in a class than ...
} const paginationAdvice: AspectAdvice = { 'around': { render: function (inherited: (data: { [ index: string ]: string }[]) => void): (data: { [index: string ]: string }[]) => void { return function (data: { [index: string ]: string }[]) { const start = this.pageNumber * this.rowsPerPage; const end = st...
{ this.pageNumber = page; this.render(this.data); }
identifier_body
paginationMixin.ts
import { AspectAdvice } from 'dojo-compose/compose'; /** * This mixin provides the ability to view discrete 'pages' of rows. The type is expressed using a class becase, as with * the case of editor and decorator, it is more concise to express a mixture of complex types and function * implementations in a class than ...
(page: number): void { this.pageNumber = page; this.render(this.data); } } const paginationAdvice: AspectAdvice = { 'around': { render: function (inherited: (data: { [ index: string ]: string }[]) => void): (data: { [index: string ]: string }[]) => void { return function (data: { [index: string ]: string }[...
gotoPage
identifier_name
paginationMixin.ts
import { AspectAdvice } from 'dojo-compose/compose'; /** * This mixin provides the ability to view discrete 'pages' of rows. The type is expressed using a class becase, as with * the case of editor and decorator, it is more concise to express a mixture of complex types and function * implementations in a class than ...
previousButton.textContent = 'Previous'; nextButton.onclick = function () { this.gotoPage(this.pageNumber + 1); }.bind(this); previousButton.onclick = function () { this.gotoPage(this.pageNumber - 1); }.bind(this); paginationNode.appendChild(previousButton); paginationNode.appen...
paginationNode.classList.add('paginationNode'); let nextButton = document.createElement('button'); let previousButton = document.createElement('button'); nextButton.textContent = 'Next';
random_line_split
paginationMixin.ts
import { AspectAdvice } from 'dojo-compose/compose'; /** * This mixin provides the ability to view discrete 'pages' of rows. The type is expressed using a class becase, as with * the case of editor and decorator, it is more concise to express a mixture of complex types and function * implementations in a class than ...
paginationNode = document.createElement('div'); paginationNode.classList.add('paginationNode'); let nextButton = document.createElement('button'); let previousButton = document.createElement('button'); nextButton.textContent = 'Next'; previousButton.textContent = 'Previous'; nextButton.on...
{ this.domNode.removeChild(paginationNode); }
conditional_block
friendlyDateRanges.js
/* friendlyDateRanges.js tests */ var test = require('tape'), friendly = require('../friendlyDateRanges'); test('tests', function (t) {
t.deepEqual(friendly(['2016-03-01', '2016-05-05']), ['March 1st','May 5th, 2016']); t.deepEqual(friendly(['2015-12-01', '2017-02-03']), ['December 1st, 2015','February 3rd, 2017']); t.deepEqual(friendly(['2015-12-01', '2016-02-03']), ['December 1st','February 3rd'], 'one month apart can be inferred it is the next...
t.deepEqual(friendly(['2022-09-05', '2023-09-04']), ['September 5th, 2022','September 4th, 2023']); t.deepEqual(friendly(['2017-01-01', '2017-01-01']), ['January 1st, 2017'], 'since we do not duplicate only return once');
random_line_split
main.rs
#![crate_name = "limonite"] #![crate_type = "bin"] extern crate docopt; extern crate rustc_serialize; #[macro_use] extern crate log; extern crate env_logger; use std::io::{BufReader, Read}; use std::fs::File; use std::path::Path; use docopt::Docopt; use lexical::lexer::Lexer; use syntax::parser::Parser; use semantic...
{ pub arg_file: String, pub flag_dump: bool, pub flag_stdin: bool, pub flag_version: bool } fn main() { env_logger::init().unwrap(); let args: Args = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if arg...
Args
identifier_name
main.rs
#![crate_name = "limonite"] #![crate_type = "bin"] extern crate docopt; extern crate rustc_serialize; #[macro_use] extern crate log; extern crate env_logger; use std::io::{BufReader, Read}; use std::fs::File; use std::path::Path; use docopt::Docopt; use lexical::lexer::Lexer; use syntax::parser::Parser; use semantic...
input_string }
random_line_split
main.rs
#![crate_name = "limonite"] #![crate_type = "bin"] extern crate docopt; extern crate rustc_serialize; #[macro_use] extern crate log; extern crate env_logger; use std::io::{BufReader, Read}; use std::fs::File; use std::path::Path; use docopt::Docopt; use lexical::lexer::Lexer; use syntax::parser::Parser; use semantic...
{ let mut input_string = String::new(); if let Err(e) = readable.read_to_string(&mut input_string) { panic!("Failed to read: {}", e); } input_string }
identifier_body
main.rs
#![crate_name = "limonite"] #![crate_type = "bin"] extern crate docopt; extern crate rustc_serialize; #[macro_use] extern crate log; extern crate env_logger; use std::io::{BufReader, Read}; use std::fs::File; use std::path::Path; use docopt::Docopt; use lexical::lexer::Lexer; use syntax::parser::Parser; use semantic...
else { readable_to_string(std::io::stdin()) }; // Tokanize the input let lexer = Lexer::new(&input_string); // Parse & Build an AST let mut parser = Parser::new(lexer); let mut ast_root = match parser.parse() { Some(ast) => ast, None => return, }; // TODO: Se...
{ let ref file_name = &args.arg_file; let path = Path::new(file_name); let file = match File::open(&path) { Ok(f) => f, Err(e) => panic!("Failed to open file: {}", e) }; readable_to_string(BufReader::new(file)) }
conditional_block
lib.rs
pub const MAX_ARGS_NUMBER: usize = 4; pub const MAX_PLAYERS: usize = 4; pub const MEM_SIZE: usize = 4 * 1024; pub const IDX_MOD: usize = MEM_SIZE / 8; pub const CHAMP_MAX_SIZE: usize = MEM_SIZE / 6; pub const REG_NUMBER: usize = 16; pub const REG_MAX: u8 = REG_NUMBER as u8; pub const CYCLE_T...
{ pub magic: u32, pub prog_name: [u8; PROG_NAME_LENGTH + 1], pub prog_size: u32, pub comment: [u8; COMMENT_LENGTH + 1], }
Header
identifier_name
lib.rs
pub const MAX_PLAYERS: usize = 4; pub const MEM_SIZE: usize = 4 * 1024; pub const IDX_MOD: usize = MEM_SIZE / 8; pub const CHAMP_MAX_SIZE: usize = MEM_SIZE / 6; pub const REG_NUMBER: usize = 16; pub const REG_MAX: u8 = REG_NUMBER as u8; pub const CYCLE_TO_DIE: usize = 1536; pub const CYCLE_D...
pub const MAX_ARGS_NUMBER: usize = 4;
random_line_split
lib.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub use rustc_back::rpath; pub use rustc_back::svh; pub use rustc_back::target_strs; pub use rustc_back::x86; pub use rustc_back::x86_64; pub mod link; pub mod lto; pub mod write; } pub mod trans; pub mod save; pub mod lib { pub use llvm; }
pub use rustc_back::arm; pub use rustc_back::mips; pub use rustc_back::mipsel;
random_line_split
GoingToZeroOrInfinity.rs
fn going(n: i32) -> f64 { let mut result = 0.0; for i in 1..n+1 { result += i as f64; result /= i as f64; } result } fn assert_fuzzy_equals(actual: f64, expected: f64) { let merr = 1.0e-6; let inrange = if expected == 0.0 { (actual.abs() <= merr) }...
() { dotest(5, 1.275); dotest(6, 1.2125); dotest(7, 1.173214); dotest(8, 1.146651); }
main
identifier_name
GoingToZeroOrInfinity.rs
fn going(n: i32) -> f64 { let mut result = 0.0; for i in 1..n+1 { result += i as f64; result /= i as f64; } result } fn assert_fuzzy_equals(actual: f64, expected: f64) { let merr = 1.0e-6; let inrange = if expected == 0.0 { (actual.abs() <= merr) }...
{ dotest(5, 1.275); dotest(6, 1.2125); dotest(7, 1.173214); dotest(8, 1.146651); }
identifier_body
GoingToZeroOrInfinity.rs
fn going(n: i32) -> f64 { let mut result = 0.0; for i in 1..n+1 { result += i as f64; result /= i as f64; } result } fn assert_fuzzy_equals(actual: f64, expected: f64) { let merr = 1.0e-6; let inrange = if expected == 0.0 {
}; if inrange == false { println!("Expected value must be near: {:e} but was:{:e}", expected, actual); } else { //println!("....... GOOD\n"); } assert_eq!(true, inrange); } fn dotest(n: i32, exp: f64) -> () { assert_fuzzy_equals(going(n), exp); } fn main() ...
(actual.abs() <= merr) } else { ((actual - expected).abs() / expected <= merr)
random_line_split
GoingToZeroOrInfinity.rs
fn going(n: i32) -> f64 { let mut result = 0.0; for i in 1..n+1 { result += i as f64; result /= i as f64; } result } fn assert_fuzzy_equals(actual: f64, expected: f64) { let merr = 1.0e-6; let inrange = if expected == 0.0 { (actual.abs() <= merr) }...
else { //println!("....... GOOD\n"); } assert_eq!(true, inrange); } fn dotest(n: i32, exp: f64) -> () { assert_fuzzy_equals(going(n), exp); } fn main() { dotest(5, 1.275); dotest(6, 1.2125); dotest(7, 1.173214); dotest(8, 1.146651); }
{ println!("Expected value must be near: {:e} but was:{:e}", expected, actual); }
conditional_block
mod.rs
//! Utilities to parse HTTP messages. #![experimental] pub use self::parser::Parser; pub use self::parser::ParseType; pub use self::parser::ParseError; pub use self::parser::MessageHandler; use std::fmt::{Formatter, FormatError, Show}; /// A list of supported HTTP versions. #[allow(non_camel_case_types)] #[deriving...
} impl Show for HttpMethod { fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> { f.pad(self.name()) } } pub mod parser; #[cfg(test)] pub mod tests;
{ self.name().char_at(pos) == c }
identifier_body
mod.rs
//! Utilities to parse HTTP messages. #![experimental] pub use self::parser::Parser; pub use self::parser::ParseType; pub use self::parser::ParseError; pub use self::parser::MessageHandler; use std::fmt::{Formatter, FormatError, Show}; /// A list of supported HTTP versions. #[allow(non_camel_case_types)] #[deriving...
(&self, pos: uint, c: char) -> bool { self.name().char_at(pos) == c } } impl Show for HttpMethod { fn fmt(&self, f: &mut Formatter) -> Result<(), FormatError> { f.pad(self.name()) } } pub mod parser; #[cfg(test)] pub mod tests;
hit
identifier_name
mod.rs
//! Utilities to parse HTTP messages. #![experimental] pub use self::parser::Parser; pub use self::parser::ParseType; pub use self::parser::ParseError; pub use self::parser::MessageHandler; use std::fmt::{Formatter, FormatError, Show}; /// A list of supported HTTP versions. #[allow(non_camel_case_types)] #[deriving...
HttpLink => "LINK", HttpLock => "LOCK", HttpMerge => "MERGE", HttpMkActivity => "MKACTIVITY", HttpMkCalendar => "MKCALENDAR", HttpMkCol => "MKCOL", HttpMove => "MOVE", HttpMsearch => "M...
HttpConnect => "CONNECT", HttpCopy => "COPY", HttpDelete => "DELETE", HttpGet => "GET", HttpHead => "HEAD",
random_line_split
digest_spec.ts
/** * @license * Copyright Google Inc. 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 {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testin...
(-size); } expect(sha1(result)).toEqual('24c2dae5c1ac6f604dbe670a60290d7ce6320b45'); }); }); }
} result = result.slice
conditional_block
digest_spec.ts
/** * @license
* * 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 {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testing_internal'; import {sha1} from '../../src/i18n/digest'; exp...
* Copyright Google Inc. All Rights Reserved.
random_line_split
digest_spec.ts
/** * @license * Copyright Google Inc. 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 {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testin...
(): void { describe('sha1', () => { it('should work on emnpty strings', () => { expect(sha1('')).toEqual('da39a3ee5e6b4b0d3255bfef95601890afd80709'); }); it('should returns the sha1 of "hello world"', () => { expect(sha1('abc')).toEqual('a9993e364706816aba3e25717850c26c9cd0d89d'); }); it('...
main
identifier_name
digest_spec.ts
/** * @license * Copyright Google Inc. 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 {beforeEach, ddescribe, describe, expect, iit, inject, it, xdescribe, xit} from '@angular/core/testing/testin...
// } // // var prefix = `你好,世界`; // var result = sha1(prefix); // for (var size = prefix.length; size < 5000; size += 101) { // result = prefix + sha1(result); // while (result.length < size) { // result += result; // } // result = result.slice(-si...
{ describe('sha1', () => { it('should work on emnpty strings', () => { expect(sha1('')).toEqual('da39a3ee5e6b4b0d3255bfef95601890afd80709'); }); it('should returns the sha1 of "hello world"', () => { expect(sha1('abc')).toEqual('a9993e364706816aba3e25717850c26c9cd0d89d'); }); it('should re...
identifier_body
dsskey.py
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
self.p = msg.get_mpint() self.q = msg.get_mpint() self.g = msg.get_mpint() self.y = msg.get_mpint() self.size = util.bit_length(self.p) def __str__(self): m = Message() m.add_string('ssh-dss') m.add_mpint(self.p) m.add_mpint(s...
self.p = None self.q = None self.g = None self.y = None self.x = None if file_obj is not None: self._from_private_key(file_obj, password) return if filename is not None: self._from_private_key_file(filename, password) return...
identifier_body
dsskey.py
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
def __str__(self): m = Message() m.add_string('ssh-dss') m.add_mpint(self.p) m.add_mpint(self.q) m.add_mpint(self.g) m.add_mpint(self.y) return str(m) def __hash__(self): h = hash(self.get_name()) h = h * 37 + hash(self.p) h = h * ...
self.g = msg.get_mpint() self.y = msg.get_mpint() self.size = util.bit_length(self.p)
random_line_split
dsskey.py
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
m.add_string(rstr + sstr) return m def verify_ssh_sig(self, data, msg): if len(str(msg)) == 40: # spies.com bug: signature has no header sig = str(msg) else: kind = msg.get_string() if kind != 'ssh-dss': return 0 ...
sstr = '\x00' * (20 - len(sstr)) + sstr
conditional_block
dsskey.py
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (a...
(self, file_obj, password): data = self._read_private_key('DSA', file_obj, password) self._decode_key(data) def _decode_key(self, data): # private key file contains: # DSAPrivateKey = { version = 0, p, q, g, y, x } try: keylist = BER(data).decode() ex...
_from_private_key
identifier_name
mod.rs
extern crate rustbox; use rustbox::Key; use state::Action; pub use self::insert_mode::InsertMode; pub use self::normal_mode::NormalMode; pub use self::replace_mode::ReplaceMode; mod insert_mode; mod normal_mode; mod replace_mode; #[derive(Eq,PartialEq,Debug,Copy,Clone,Hash)] pub enum ModeType { Insert, Norm...
/// The name of the mode. Displayed in the bottom bar. fn display(&self) -> &'static str; }
{ None }
identifier_body
mod.rs
extern crate rustbox; use rustbox::Key; use state::Action; pub use self::insert_mode::InsertMode; pub use self::normal_mode::NormalMode; pub use self::replace_mode::ReplaceMode; mod insert_mode; mod normal_mode; mod replace_mode; #[derive(Eq,PartialEq,Debug,Copy,Clone,Hash)] pub enum ModeType { Insert, Norm...
(&self) -> Option<u16> { None } /// The name of the mode. Displayed in the bottom bar. fn display(&self) -> &'static str; }
color
identifier_name
mod.rs
extern crate rustbox; use rustbox::Key; use state::Action; pub use self::insert_mode::InsertMode; pub use self::normal_mode::NormalMode; pub use self::replace_mode::ReplaceMode; mod insert_mode; mod normal_mode; mod replace_mode; #[derive(Eq,PartialEq,Debug,Copy,Clone,Hash)] pub enum ModeType { Insert, Norm...
fn color(&self) -> Option<u16> { None } /// The name of the mode. Displayed in the bottom bar. fn display(&self) -> &'static str; }
fn on_exit(&self) -> Option<Action> { None } /// Color to use for the bottom bar.
random_line_split
index.ts
/* * Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights...
(): Observable<Viewport> { return combineLatest([ watchViewportOffset(), watchViewportSize() ]) .pipe( map(([offset, size]) => ({ offset, size })), shareReplay(1) ) } /** * Watch viewport relative to element * * @param el - Element * @param options - Options * * @return Viewport o...
watchViewport
identifier_name
index.ts
/* * Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights...
/* ---------------------------------------------------------------------------- * Helper types * ------------------------------------------------------------------------- */ /** * Watch at options */ interface WatchAtOptions { header$: Observable<Header> /* Header observable */ viewport$: Observable<...
}
random_line_split
index.ts
/* * Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights...
/** * Watch viewport relative to element * * @param el - Element * @param options - Options * * @return Viewport observable */ export function watchViewportAt( el: HTMLElement, { header$, viewport$ }: WatchAtOptions ): Observable<Viewport> { const size$ = viewport$ .pipe( distinctUntilKeyChanged(...
{ return combineLatest([ watchViewportOffset(), watchViewportSize() ]) .pipe( map(([offset, size]) => ({ offset, size })), shareReplay(1) ) }
identifier_body
position.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/. */ //! CSS handling for the computed value of //! [`position`][position]s //! //! [position]: https://drafts.csswg.or...
}
{ self.0.to_css(dest) }
identifier_body
position.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/. */ //! CSS handling for the computed value of //! [`position`][position]s //! //! [position]: https://drafts.csswg.or...
(pub LengthOrPercentage); impl ToCss for VerticalPosition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } }
VerticalPosition
identifier_name
position.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/. */ //! CSS handling for the computed value of //! [`position`][position]s //! //! [position]: https://drafts.csswg.or...
} } #[derive(Debug, Clone, PartialEq, Copy)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct VerticalPosition(pub LengthOrPercentage); impl ToCss for VerticalPosition { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } }
self.0.to_css(dest)
random_line_split
ezrss.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
if title and url: logger.log(u"RSS Feed provider: [" + self.name + "] Attempting to add item to cache: " + title, logger.DEBUG) results.append(curItem) return results def _get_title_and_url(self, item): (title, url) = generic.TorrentProvider._get_title_a...
(title, url) = self._get_title_and_url(curItem)
random_line_split
ezrss.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
return 'ezrss.png' def getQuality(self, item, anime=False): try: quality = Quality.sceneQuality(item.filename, anime) except: quality = Quality.UNKNOWN return quality def findSearchResults(self, show, episodes, search_mode, manualSearch=False, downCurQ...
def __init__(self): self.urls = {'base_url': 'https://www.ezrss.it/'} self.url = self.urls['base_url'] generic.TorrentProvider.__init__(self, "EZRSS") self.supportsBacklog = True self.supportsFrench = False self.enabled = False self.ratio = None ...
identifier_body
ezrss.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
(tvcache.TVCache): def __init__(self, provider): tvcache.TVCache.__init__(self, provider) # only poll EZRSS every 15 minutes max self.minTime = 15 def _getRSSData(self): rss_url = self.provider.url + 'feed/' logger.log(self.provider.name + " cache update URL: " + rss_...
EZRSSCache
identifier_name
ezrss.py
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
search_url = self.url + 'search/index.php?' + urllib.urlencode(params) logger.log(u"Search string: " + search_url, logger.DEBUG) results = [] for curItem in self.cache.getRSSFeed(search_url, items=['entries'])['entries'] or []: (title, url) = self._get_title_and_url(curI...
params.update(search_params)
conditional_block
jalaliDate.js
JalaliDate = { g_days_in_month : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], j_days_in_month : [31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29] }; JalaliDate.jalaliToGregorian = function (j_y, j_m, j_d) { j_y = parseInt(j_y); j_m = parseInt(j_m); j_d = parseInt(j_d); var jy = j_y - 979; var jm = j_m - 1; ...
var jy = 979 + 33 * j_np + 4 * parseInt(j_day_no / 1461); j_day_no %= 1461; if (j_day_no >= 366) { jy += parseInt((j_day_no - 1) / 365); j_day_no = (j_day_no - 1) % 365; } for (var i = 0; i < 11 && j_day_no >= JalaliDate.j_days_in_month[i]; ++i) { j_day_no -= JalaliDate.j_days_in_month[i]; } var jm =...
var j_day_no = g_day_no - 79; var j_np = parseInt(j_day_no / 12053); j_day_no %= 12053;
random_line_split
lib.rs
// Copyright (c) 2016 warheadhateus developers // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be cop...
}
{}
identifier_body
lib.rs
// Copyright (c) 2016 warheadhateus developers // // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. All files in the project carrying such notice may not be cop...
mod sender; mod server; mod ssh; mod sshd; pub use client::Client; pub use endpoint::Udp; pub use error::NailErr; pub use receiver::Receiver; pub use sender::Sender; pub use server::{NailMessage, NailMessageHandler, Server}; pub use sshd::{SshDaemon, SshPacketHandler}; /// Convenience Result for use with `NailErr`. p...
random_line_split