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
markdown_to_html.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import codecs import...
(Task): """Generate HTML from Markdown docs.""" @classmethod def register_options(cls, register): register('--code-style', choices=list(get_all_styles()), default='friendly', fingerprint=True, help='Use this stylesheet for code highlights.') register('--open', type=bool, ...
MarkdownToHtml
identifier_name
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
############################################################################## {'name': 'Stock Reservation', 'summary': 'Stock reservations on products', 'version': '0.2', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Warehouse', 'license': 'AGPL-3', 'complexity': 'normal', 'images': [],...
# You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #
random_line_split
proc-macro-crate-in-paths.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(input: TokenStream) -> TokenStream { input }
derive_template
identifier_name
proc-macro-crate-in-paths.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ input }
identifier_body
proc-macro-crate-in-paths.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#![crate_type = "proc-macro"] #![deny(rust_2018_compatibility)] #![feature(rust_2018_preview)] extern crate proc_macro; use proc_macro::TokenStream; #[proc_macro_derive(Template, attributes(template))] pub fn derive_template(input: TokenStream) -> TokenStream { input }
// compile-pass // force-host // no-prefer-dynamic
random_line_split
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let (p, ch) = stream(); let ch = SharedChan::new(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut actual = 0u; for uint::range(0u, n) |_i| { ...
{ c.send(~i); }
identifier_body
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert!(expected == actual); }
}
random_line_split
unique-send-2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(c: &SharedChan<~uint>, i: uint) { c.send(~i); } pub fn main() { let (p, ch) = stream(); let ch = SharedChan::new(ch); let n = 100u; let mut expected = 0u; for uint::range(0u, n) |i| { let ch = ch.clone(); task::spawn(|| child(&ch, i) ); expected += i; } let mut...
child
identifier_name
materialfilter.js
var filtergrid = "#materialgrid_gw"; var filtermodal = "#MaterialFilter"; var filtersearch = "MaterialSearch"; var modalShow = function () { $(filtergrid).find('.filter_button').click(function (e) { e.preventDefault(); $(filtermodal).modal('show').find('.modal-body').html('<div style="height: 150px...
var formgrid = $("form.gridview-filter-form"); var input = $("input[name='" + filtersearch + "[_filter]']"); if ($(filtermodal).length && $(filtermodal)[0].statusform === 1) { if (!input.length) formgrid.append($('<input type="hidden" class="form-control" name="' + f...
var formcontain = $("form" + filtermodal + "-form").serialize();
random_line_split
materialfilter.js
var filtergrid = "#materialgrid_gw"; var filtermodal = "#MaterialFilter"; var filtersearch = "MaterialSearch"; var modalShow = function () { $(filtergrid).find('.filter_button').click(function (e) { e.preventDefault(); $(filtermodal).modal('show').find('.modal-body').html('<div style="height: 150px...
ve(); return true; }); $(document).on("keyup", "input.searchfilterform", function () { $("div.insideforms").find("div.panelblock").hide(); $("label").each(function (key, value) { var searchinput = ($("input.searchfilterform").val()).toUpperCase(); var labelinpu...
formgrid.append($('<input type="hidden" class="form-control" name="' + filtersearch + '[_filter]" />').val(formcontain)); else input.val(formcontain); } else if (input.length) input.remo
conditional_block
FormElement-dbg.js
* @name sap.ui.layout.form.FormElement#getFields * @function */ /** * Inserts a field into the aggregation named <code>fields</code>. * * @param {sap.ui.core.Control} * oField the field to insert; if empty, nothing is inserted * @param {int} * iIndex the <code>0</code>-based index the f...
}
random_line_split
FormElement-dbg.js
empty, nothing is inserted * @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining * @public * @name sap.ui.layout.form.FormElement#addField * @function */ /** * Removes an field from the aggregation named <code>fields</code>. * * @param {int | string | sap.ui.core.Control} vFiel...
{ return true; }
conditional_block
resources.js
'use strict'; angular.module('openshiftConsole') .directive('overviewDeployment', function($location, $timeout, LabelFilter) { return { restrict: 'E', scope: { // Replication controller / deployment fields rc: '=', deploymentConfigId: '=', deploymentConfigMissing: '=', ...
return { restrict: 'E', scope: { podTemplate: '=', imagesByDockerReference: '=', builds: '=' }, templateUrl: 'views/_pod-template.html' }; }) .directive('pods', function() { return { restrict: 'E', scope: { pods: '=', projectNam...
}, templateUrl: 'views/_overview-monopod.html' }; }) .directive('podTemplate', function() {
random_line_split
resources.js
'use strict'; angular.module('openshiftConsole') .directive('overviewDeployment', function($location, $timeout, LabelFilter) { return { restrict: 'E', scope: { // Replication controller / deployment fields rc: '=', deploymentConfigId: '=', deploymentConfigMissing: '=', ...
}; } }; }) .directive('podContent', function() { // sub-directive used by the pods directive return { restrict: 'E', scope: { pod: '=', troubled: '=' }, templateUrl: 'views/directives/_pod-content.html' }; }) .directive('triggers', functio...
{ $event.stopPropagation(); }
conditional_block
express-handlebars.d.ts
// Type definitions for express-handlebars // Project: https://github.com/ericf/express-handlebars // Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>, Igor Dultsev <https://github.com/yhaskell> // Definitions: https://github.com/borisyankov/DefinitelyTyped /// <reference path="../es6-promise/es6-...
helpers?: any; partials?: any; } interface ExphbsOptions { handlebars?: any; extname?: string; layoutsDir?: string; partialsDir?: any; defaultLayout?: string; helpers?: any; compilerOptions?: any; } interface Exphbs { engine: Function; extname: string; compiled: Object;...
random_line_split
mod.rs
// // SOS: the Stupid Operating System // by Eliza Weisman (eliza@elizas.website) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! `x86_64` architecture-specific implementation. // pub ...
() { asm!("movabsq $$(stack_top), %rsp"); asm!("mov ax, 0 mov ss, ax mov ds, ax mov es, ax mov fs, ax mov gs, ax call arch_init" :::: "intel"); } /// Entry point for architecture-specific kernel init /// /// This expects to be passed the addr...
long_mode_init
identifier_name
mod.rs
//
// SOS: the Stupid Operating System // by Eliza Weisman (eliza@elizas.website) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! `x86_64` architecture-specific implementation. // pub mod...
random_line_split
mod.rs
// // SOS: the Stupid Operating System // by Eliza Weisman (eliza@elizas.website) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! `x86_64` architecture-specific implementation. // pub ...
} //-- enable flags needed for paging ------------------------------------ unsafe { // control_regs::cr0::enable_write_protect(true); // kinfoln!(dots: " . ", "Page write protect ENABED" ); let efer = msr::read(msr::IA32_EFER); trace!("EFER = {:#x}", efer); msr...
{ params.mem_map.push(a); }
conditional_block
mod.rs
// // SOS: the Stupid Operating System // by Eliza Weisman (eliza@elizas.website) // // Copyright (c) 2015-2017 Eliza Weisman // Released under the terms of the MIT license. See `LICENSE` in the root // directory of this repository for more information. // //! `x86_64` architecture-specific implementation. // pub ...
/// Entry point for architecture-specific kernel init /// /// This expects to be passed the address of a valid /// Multiboot 2 info struct. It's the bootloader's responsibility to ensure /// that this is passed in the correct register as expected by the calling /// convention (`edi` on x86). If this isn't there, you ...
{ asm!("movabsq $$(stack_top), %rsp"); asm!("mov ax, 0 mov ss, ax mov ds, ax mov es, ax mov fs, ax mov gs, ax call arch_init" :::: "intel"); }
identifier_body
Callouts.js
import s from './Callouts.css'; import React, { PropTypes } from 'react'; import numbro from 'numbro'; function diversityAtParityOrGreater(conf) { return conf.diversityPercentage >= 50; } function confFromCurrentYear(conf) { return conf.year == (new Date()).getFullYear(); } function diversityAccumulator(accumula...
render() { return ( <div className={s.container}> <div className="row"> <div className="col-sm-2"> <div className={s.title}>Conferences<br/>tracked</div> <div className={s.pop}>{this.state.numberOfConfs}</div> </div> <div className="col-sm-2"> ...
{ super(props); this.currentYearConfs = props.confs.filter(confFromCurrentYear); this.state = { confs: props.confs, bestPerformer: props.confs.sort(diversitySorter)[0], numberOfConfs: props.confs.length, numberOfConfsAtParityOrGreater: props.confs.filter(diversityAtParityOrGreater)...
identifier_body
Callouts.js
import s from './Callouts.css'; import React, { PropTypes } from 'react'; import numbro from 'numbro'; function diversityAtParityOrGreater(conf) { return conf.diversityPercentage >= 50; } function confFromCurrentYear(conf) { return conf.year == (new Date()).getFullYear(); } function diversityAccumulator(accumula...
return 0; } class Callouts extends React.Component { constructor(props) { super(props); this.currentYearConfs = props.confs.filter(confFromCurrentYear); this.state = { confs: props.confs, bestPerformer: props.confs.sort(diversitySorter)[0], numberOfConfs: props.confs.length, ...
{ return -1; }
conditional_block
Callouts.js
import s from './Callouts.css'; import React, { PropTypes } from 'react'; import numbro from 'numbro'; function
(conf) { return conf.diversityPercentage >= 50; } function confFromCurrentYear(conf) { return conf.year == (new Date()).getFullYear(); } function diversityAccumulator(accumulator, conf) { return accumulator + conf.diversityPercentage; } function diversitySorter(confA, confB) { if (confA.diversityPercentage...
diversityAtParityOrGreater
identifier_name
Callouts.js
import s from './Callouts.css'; import React, { PropTypes } from 'react'; import numbro from 'numbro'; function diversityAtParityOrGreater(conf) { return conf.diversityPercentage >= 50; } function confFromCurrentYear(conf) { return conf.year == (new Date()).getFullYear(); } function diversityAccumulator(accumula...
bestPerformer: props.confs.sort(diversitySorter)[0], numberOfConfs: props.confs.length, numberOfConfsAtParityOrGreater: props.confs.filter(diversityAtParityOrGreater).length, averageDiversity: props.confs.reduce(diversityAccumulator, 0) / props.confs.length, averageDiversityCurrentYear: th...
this.state = { confs: props.confs,
random_line_split
imports.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() {} } mod bar { pub fn f() {} } pub fn f() -> bool { true } // Items and explicit imports shadow globs. fn g() { use foo::*; use bar::*; fn f() -> bool { true } let _: bool = f(); } fn h() { use foo::*; use bar::*; use f; let _: bool = f(); } // Here, there appears to be shadowing ...
f
identifier_name
imports.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let _: bool = f(); } fn h() { use foo::*; use bar::*; use f; let _: bool = f(); } // Here, there appears to be shadowing but isn't because of namespaces. mod b { use foo::*; // This imports `f` in the value namespace. use super::b as f; // This imports `f` only in the type namespace, ...
{ true }
identifier_body
imports.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use foo::*; use bar::*; fn f() -> bool { true } let _: bool = f(); } fn h() { use foo::*; use bar::*; use f; let _: bool = f(); } // Here, there appears to be shadowing but isn't because of namespaces. mod b { use foo::*; // This imports `f` in the value namespace. use super::b...
// Items and explicit imports shadow globs. fn g() {
random_line_split
cmd.rs
use clap::{App, Arg}; use generators::common::{GenConfig, GenMode}; use itertools::Itertools; use std::str::FromStr; #[derive(Clone, Debug)] pub struct CommandLineArguments { pub codegen_key: Option<String>, pub demo_key: Option<String>, pub bench_key: Option<String>, pub generation_mode: GenMode, ...
let mut config = GenConfig::new(); if !config_string.is_empty() { for mut chunk in &config_string.split(' ').chunks(2) { let key = chunk.next().unwrap(); let value = u64::from_str(chunk.next().expect("Bad config")).expect("Invalid config value"); confi...
"special_random" => GenMode::SpecialRandom, _ => panic!("Invalid generation mode"), }; let config_string = matches.value_of("config").unwrap_or("");
random_line_split
cmd.rs
use clap::{App, Arg}; use generators::common::{GenConfig, GenMode}; use itertools::Itertools; use std::str::FromStr; #[derive(Clone, Debug)] pub struct CommandLineArguments { pub codegen_key: Option<String>, pub demo_key: Option<String>, pub bench_key: Option<String>, pub generation_mode: GenMode, ...
Arg::with_name("limit") .short("l") .long("limit") .help("Specifies the maximum number of elements to generate") .takes_value(true), ) .arg( Arg::with_name("out") .short("o") .long("ou...
{ let matches = App::new(name) .version("0.1.0") .author("Mikhail Hogrefe <mikhailhogrefe@gmail.com>") .about("Runs demos and benchmarks for malachite-base functions.") .arg( Arg::with_name("generation_mode") .short("m") .long("generation_m...
identifier_body
cmd.rs
use clap::{App, Arg}; use generators::common::{GenConfig, GenMode}; use itertools::Itertools; use std::str::FromStr; #[derive(Clone, Debug)] pub struct
{ pub codegen_key: Option<String>, pub demo_key: Option<String>, pub bench_key: Option<String>, pub generation_mode: GenMode, pub config: GenConfig, pub limit: usize, pub out: String, } pub fn read_command_line_arguments(name: &str) -> CommandLineArguments { let matches = App::new(name...
CommandLineArguments
identifier_name
format.py
""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_form...
def _get_input_type(data): """Returns the input_type data structure that defines an input type and its constraints for validation.""" if 'id' not in data or 'input_type' not in data: return None input_type = dict( id=data['id'], base_type=data['input_type'] ) input_typ...
if input_type['base_type'] == 'Array': input_type['subtype'] = input_types[input_type['subtype']] elif input_type['base_type'] == 'Abstract': _substitute_implementations() _substitute_default_descendant() elif input_type['base_type'] == 'Record': _substitu...
conditional_block
format.py
""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_form...
type_ = input_types[id_] impls[type_['name']] = type_ input_type['implementations'] = impls def _substitute_default_descendant(): """Replaces default descendant id with input_type.""" id_ = input_type.get('default_descendant', None) if id_ is not None: ...
def _substitute_implementations(): """Replaces implementation ids with input_types.""" impls = {} for id_ in input_type['implementations']:
random_line_split
format.py
""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_form...
(data): """Parses the format range properties - min, max.""" input_type = {} try: input_type['min'] = data['range'][0] except (KeyError, TypeError): # set default value input_type['min'] = float('-inf') try: input_type['max'] = data['range'][1] except (KeyError, TypeErro...
_parse_range
identifier_name
format.py
""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_form...
for __, value in input_type['keys'].items(): value['type'] = input_types[value['type']] # pylint: disable=unused-variable, invalid-name for __, input_type in input_types.items(): if input_type['base_type'] == 'Array': input_type['subtype'] = input_types[input_type['subty...
"""Replaces ids or type names with python object references.""" input_type = {} def _substitute_implementations(): """Replaces implementation ids with input_types.""" impls = {} for id_ in input_type['implementations']: type_ = input_types[id_] impls[type_['name'...
identifier_body
parse_iso_20022_files.py
import logging from django.core.management.base import BaseCommand from payment.postfinance_connector import ISO2022Parser log = logging.getLogger('tq') class Command(BaseCommand): help = '(re)parse ISO 20022 files, ignoring duplicates' def add_arguments(self, parser): parser.add_argument( ...
log.info('run management command: {}'.format(__file__)) parser = ISO2022Parser() count = parser.parse(reparse=options['reparse'], dry_run=options['dry_run']) log.info('found and parsed {} new transactions'.format(count))
identifier_body
parse_iso_20022_files.py
import logging from django.core.management.base import BaseCommand from payment.postfinance_connector import ISO2022Parser log = logging.getLogger('tq') class Command(BaseCommand): help = '(re)parse ISO 20022 files, ignoring duplicates' def
(self, parser): parser.add_argument( '--dry-run', action='store_true', dest='dry_run', default=False, help='dry run', ) parser.add_argument( '--reparse', action='store_true', dest='reparse', ...
add_arguments
identifier_name
parse_iso_20022_files.py
import logging
log = logging.getLogger('tq') class Command(BaseCommand): help = '(re)parse ISO 20022 files, ignoring duplicates' def add_arguments(self, parser): parser.add_argument( '--dry-run', action='store_true', dest='dry_run', default=False, help='d...
from django.core.management.base import BaseCommand from payment.postfinance_connector import ISO2022Parser
random_line_split
namelists.py
from the original core.nml and phys.nml files included in 2006 codebase. # where the value is the same as the default in the code base, it is commented out # and therefore not included in the namelist. # Where the value is different, the code default is shown in an inline comment basic = f90nml.Namelist({}) basic['...
#'ir_tau_eq': 6.0, #'del_sol': 1.4, 'atm_abs': 0.2 # default: 0.0 } basic['mixed_layer_nml'] = { 'albedo_value': 0.27, # default: 0.06 'depth': 100.0, # default: 40.0 'tconst': 285., # default: 305.0 #'delta_T': 40., 'prescribe_initial_dist': True, 'evapora...
#'solar_constant': 1360., #'solar_exponent': 4.0, #'ir_tau_pole': 1.5,
random_line_split
codeChecksBenchmarks.ts
import {codechecks, CodeChecksReport} from "@codechecks/client"; import {BENCHMARK_OPTIONS} from "./constants"; import {BenchmarkOptions} from "./interfaces/Benchmarks"; import {Benchmarks, getBenchmarks} from "./utils/getBenchmarks"; import {getReport} from "./utils/getReport"; const markdownTable = require("markdown-...
() { const options: BenchmarkOptions = BENCHMARK_OPTIONS; const currentBenchmarks = await getBenchmarks(options); await codechecks.saveValue(benchmarksKey, currentBenchmarks); if (!codechecks.isPr()) { return; } const baselineBenchmarks = await codechecks.getValue<Benchmarks>(benchmarksKey); const re...
codeChecksBenchmarks
identifier_name
codeChecksBenchmarks.ts
import {codechecks, CodeChecksReport} from "@codechecks/client"; import {BENCHMARK_OPTIONS} from "./constants"; import {BenchmarkOptions} from "./interfaces/Benchmarks"; import {Benchmarks, getBenchmarks} from "./utils/getBenchmarks"; import {getReport} from "./utils/getReport"; const markdownTable = require("markdown-...
const baselineBenchmarks = await codechecks.getValue<Benchmarks>(benchmarksKey); const report = getCodechecksReport(currentBenchmarks, baselineBenchmarks, options); await codechecks.report(report); }
{ return; }
conditional_block
codeChecksBenchmarks.ts
import {codechecks, CodeChecksReport} from "@codechecks/client"; import {BENCHMARK_OPTIONS} from "./constants"; import {BenchmarkOptions} from "./interfaces/Benchmarks"; import {Benchmarks, getBenchmarks} from "./utils/getBenchmarks"; import {getReport} from "./utils/getReport"; const markdownTable = require("markdown-...
export default async function codeChecksBenchmarks() { const options: BenchmarkOptions = BENCHMARK_OPTIONS; const currentBenchmarks = await getBenchmarks(options); await codechecks.saveValue(benchmarksKey, currentBenchmarks); if (!codechecks.isPr()) { return; } const baselineBenchmarks = await codech...
{ const {description, statistics} = getReport(current, baseline, options); return { name: "Benchmarks", status: "success", shortDescription: description, longDescription: markdownTable(statistics) }; }
identifier_body
codeChecksBenchmarks.ts
import {codechecks, CodeChecksReport} from "@codechecks/client"; import {BENCHMARK_OPTIONS} from "./constants"; import {BenchmarkOptions} from "./interfaces/Benchmarks"; import {Benchmarks, getBenchmarks} from "./utils/getBenchmarks"; import {getReport} from "./utils/getReport"; const markdownTable = require("markdown-...
return; } const baselineBenchmarks = await codechecks.getValue<Benchmarks>(benchmarksKey); const report = getCodechecksReport(currentBenchmarks, baselineBenchmarks, options); await codechecks.report(report); }
const options: BenchmarkOptions = BENCHMARK_OPTIONS; const currentBenchmarks = await getBenchmarks(options); await codechecks.saveValue(benchmarksKey, currentBenchmarks); if (!codechecks.isPr()) {
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { ProductComponent } from...
{ }
AppModule
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { AppComponent } from './app.component'; import { ProductComponent } from...
declarations: [ AppComponent, AppMenuComponent, StorageComponent, WelcomeComponent, LoginComponent, ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot([ { path: 'welcome', component: WelcomeComponent, canActivate: [AuthGuard] }, { path: 'lo...
random_line_split
app_controller.js
App.ApplicationController = Ember.Controller.extend({ currentUser: {}, isLoggedIn: false, schools: [], init: function() { this._super(); // first check for the logged in user var hasCurrrentUser = (Parse.User.current() != null); this.set('isLoggedIn', hasCurrrentUser); if(hasCurrrentUser) { thi...
} } ); }, // This function will retreive the snapshots for the user getCurrentUserSnaps: function(user) { var _self = this; App.Snapshot.find(undefined, user, function(results, error) { if (!error) { if(results && results.length > 0) { _self.get('currentUser').set...
{ _self.get('currentUser').set('events', results); }
conditional_block
app_controller.js
App.ApplicationController = Ember.Controller.extend({ currentUser: {}, isLoggedIn: false, schools: [], init: function() { this._super(); // first check for the logged in user var hasCurrrentUser = (Parse.User.current() != null); this.set('isLoggedIn', hasCurrrentUser); if(hasCurrrentUser) { thi...
var _self = this; App.Event.find(undefined, user, function(results, error) { if (!error) { if(results && results.length > 0) { _self.get('currentUser').set('events', results); } } } ); }, // This function will retreive the snapshots for the user getCurrentUse...
Parse.User.logOut(); window.location = "/"; }, // This function will retreive the events for the user getCurrentUserEvents: function(user) {
random_line_split
custom.js
height(); }); } else { closeVisibleSubMenu(); parent.addClass('nav-active'); sub.slideDown(200, function(){ adjustmainpanelheight(); }); } } return false; }); function closeVisibleSubMenu() { jQuery('.l...
{ // Adjust mainpanel height var docHeight = jQuery(document).height(); if(docHeight > jQuery('.mainpanel').height()) jQuery('.mainpanel').height(docHeight); } adjustmainpanelheight(); // Tooltip jQuery('.tooltips').tooltip({ container: 'body'}); // Popover jQuery('.popo...
justmainpanelheight()
identifier_name
custom.js
height(); }); } else { closeVisibleSubMenu(); parent.addClass('nav-active'); sub.slideDown(200, function(){ adjustmainpanelheight(); }); } } return false; }); function closeVisibleSubMenu() { jQuery('.l...
adjustmainpanelheight(); // Tooltip jQuery('.tooltips').tooltip({ container: 'body'}); // Popover jQuery('.popovers').popover(); // Close Button in Panels jQuery('.panel .panel-close').click(function(){ jQuery(this).closest('.panel').fadeOut(200); return false; }); // Form Tog...
// Adjust mainpanel height var docHeight = jQuery(document).height(); if(docHeight > jQuery('.mainpanel').height()) jQuery('.mainpanel').height(docHeight); }
identifier_body
custom.js
height(); }); } else {
} return false; }); function closeVisibleSubMenu() { jQuery('.leftpanel .nav-parent').each(function() { var t = jQuery(this); if(t.hasClass('nav-active')) { t.find('> ul').slideUp(200, function(){ t.removeClass('nav-active'); }); ...
closeVisibleSubMenu(); parent.addClass('nav-active'); sub.slideDown(200, function(){ adjustmainpanelheight(); }); }
conditional_block
custom.js
height(); }); } else { closeVisibleSubMenu(); parent.addClass('nav-active'); sub.slideDown(200, function(){ adjustmainpanelheight(); }); } } return false; }); function closeVisibleSubMenu() { jQuery('.l...
}, function(){ jQuery(this).removeClass('nav-hover'); }); // Menu Toggle jQuery('.menutoggle').click(function(){ var body = jQuery('body'); var bodypos = body.css('position'); if(bodypos != 'relative') { if(!body.hasClass('leftpanel-collapsed')) { body.addCl...
// Add class everytime a mouse pointer hover over it jQuery('.nav-bracket > li').hover(function(){ jQuery(this).addClass('nav-hover');
random_line_split
index.tsx
import React from 'react' import styled from 'styled-components' import { Link } from 'react-router-dom' import ColoredChannelLink from 'v2/components/UI/ColoredChannelLink' import StickyBreadcrumbPath from 'v2/components/UI/StickyBreadcrumbPath' import BorderedLock from 'v2/components/UI/BorderedLock' import { getBr...
)} </Link> </StickyBreadcrumbPath.Crumb>, <StickyBreadcrumbPath.Crumb key="tail"> <ColoredChannelLink as={Link} to={{ pathname: channel.href, state: getBreadcrumbPath(channel), }} visibility={cha...
{channel.counts.collaborators > 0 && ( <CollaboratorCount> {' '} (+{channel.counts.collaborators}) </CollaboratorCount>
random_line_split
configs.js
(place, timestamp) { if (typeof timestamp == "string") { timestamp = parseInt(timestamp, 10) * 1000; } const d = dayjs(timestamp); $("#" + place + "-month").val(d.month() + 1); // Months are zero indexed (https://day.js.org/docs/en/get-set/month) $("#" + place + "-day").val(d.date()); $("#" + place + "-...
loadTimestamp
identifier_name
configs.js
MMMM Do YYYY, h:mm:ss a z (zzz)") ); $("#" + place + "-zonetime").val( utc.tz(timezone_string).format("dddd, MMMM Do YYYY, h:mm:ss a z (zzz)") ); } else { $("#" + place).val(""); $("#" + place + "-local").val(""); $("#" + place + "-zonetime").val(""); } } function convertDateToMoment...
Object.keys(obj).forEach(function(x) { if (obj[x] === "true") { params[x] = true; } else if (obj[x] === "false") { params[x] = false; } else { params[x] = obj[x]; } }); CTFd.api.patch_config_list({}, params).then(function(_response) { if (_response.success) { window....
{ if (obj.mail_username === "") { delete obj.mail_username; } if (obj.mail_password === "") { delete obj.mail_password; } }
conditional_block
configs.js
, MMMM Do YYYY, h:mm:ss a z (zzz)") ); $("#" + place + "-zonetime").val( utc.tz(timezone_string).format("dddd, MMMM Do YYYY, h:mm:ss a z (zzz)") ); } else { $("#" + place).val(""); $("#" + place + "-local").val(""); $("#" + place + "-zonetime").val(""); } } function convertDateToMomen...
if (day_str.length == 1) { day_str = "0" + day_str; } let hour_str = hour.toString(); if (hour_str.length == 1) { hour_str = "0" + hour_str; } let min_str = minute.toString(); if (min_str.length == 1) { min_str = "0" + min_str; } // 2013-02-08 24:00 const date_string = year.toStri...
if (month_num.length == 1) { month_num = "0" + month_num; } let day_str = day.toString();
random_line_split
configs.js
, MMMM Do YYYY, h:mm:ss a z (zzz)") ); $("#" + place + "-zonetime").val( utc.tz(timezone_string).format("dddd, MMMM Do YYYY, h:mm:ss a z (zzz)") ); } else { $("#" + place).val(""); $("#" + place + "-local").val(""); $("#" + place + "-zonetime").val(""); } } function convertDateToMomen...
title: "Error!", body: "Logo uploading failed!", button: "Okay" }); } }); }); } function switchUserMode(event) { event.preventDefault(); if ( confirm( "Are you sure you'd like to switch user modes?\n\nAll user submissions, awards, unlocks, an...
{ event.preventDefault(); let form = event.target; helpers.files.upload(form, {}, function(response) { const f = response.data[0]; const params = { value: f.location }; CTFd.fetch("/api/v1/configs/ctf_logo", { method: "PATCH", body: JSON.stringify(params) }) .then(funct...
identifier_body
cabi.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(ty: Type, attr: option::Option<Attribute>) -> ArgType { ArgType { kind: Indirect, ty: ty, cast: option::None, pad: option::None, attr: attr } } pub fn is_direct(&self) -> bool { return self.kind == Direct; } pub fn is...
indirect
identifier_name
cabi.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} /// Metadata describing how the arguments to a native function /// should be passed in order to respect the native ABI. /// /// I will do my best to describe this structure, but these /// comments are reverse-engineered and may be inaccurate. -NDM pub struct FnType { /// The LLVM types of each argument. arg...
{ return self.kind == Indirect; }
identifier_body
cabi.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// I will do my best to describe this structure, but these /// comments are reverse-engineered and may be inaccurate. -NDM pub struct FnType { /// The LLVM types of each argument. arg_tys: ~[ArgType], /// LLVM return type. ret_ty: ArgType, } pub fn compute_abi_info(ccx: &CrateContext, ...
random_line_split
middlewares.py
GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # KManga 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 PARTICUL...
else: logger.error('No proxy found for %s' % spider.name) def process_response(self, request, response, spider): if 'proxy' in request.meta: logger.debug('Process respose - proxy: %s, url: %s, ' 'status: %s, flags: %s' % ( ...
logger.info('Using proxy <%s> for request' % proxy) request.meta['proxy'] = 'http://%s' % proxy.proxy # Disable redirection when a proxy is in use request.meta['dont_redirect'] = True
conditional_block
middlewares.py
GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # KManga 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 PARTICUL...
else: logger.error('No proxy found for %s' % spider.name) def process_response(self, request, response, spider): if 'proxy' in request.meta: logger.debug('Process respose - proxy: %s, url: %s, ' 'status: %s, flags: %s' % ( ...
has_operation = hasattr(spider, '_operation') operations = ('catalog', 'collection', 'latest', 'manga') if not has_operation or spider._operation not in operations: return logger.debug('Process request - proxy: %s, url: %s' % ( request.meta['proxy'] if 'proxy' in request...
identifier_body
middlewares.py
GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # KManga 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 PARTICUL...
if response.status in self.retry_error_codes: self._delete_proxy_from_request(request, spider) elif response.status in self.error_codes: # Some of the error codes are redirects, we need to # check if this a valid redirect, to maintain the ...
response.status, response.flags))
random_line_split
middlewares.py
General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # KManga 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 P...
(self, request, response, spider): """Resolve the CloudFlare challenge.""" request_response = response if hasattr(spider, 'cloudflare') and spider.cloudflare: if response.status == 503 and response.headers['Server']: logger.debug('CloudFlare challenge detected') ...
process_response
identifier_name
users.test.js
'use strict'; // eslint-disable-line semi const request = require('supertest'); const {expect} = require('chai'); const db = require('APP/db'); const app = require('./start'); describe('/api/users', () => { before('Await database sync', () => db.didSync); afterEach('Clear the tables', () => db.truncate({ cascade...
email: 'eve@interloper.com', password: '23456', }) .redirects(1) .then(res => expect(res.body).to.contain({ email: 'eve@interloper.com' })) ); }); }); });
random_line_split
Business.js
import React from 'react'; import pure from 'recompose/pure';
<path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z" /> </SvgIcon>; Business = pure(Business); Business.muiName = 'SvgIcon'; export default Business;
import SvgIcon from 'material-ui/SvgIcon'; let Business = props => <SvgIcon {...props}>
random_line_split
lalframe.py
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
(stream, channel, start, duration): try: dtype = lalframe.FrStreamGetTimeSeriesType(channel, stream) except RuntimeError as exc: if str(exc).lower() == "wrong name": exc.args = "channel '{}' not found".format(channel), raise reader = lalutils.find_typed_function(dtype, 'F...
_read_channel
identifier_name
lalframe.py
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
# create new frame frame = lalframe.FrameNew(start, duration, name, run, 0, detectors) for series in tsdict.values(): # get type ctype = ( type or getattr(series.channel, "_ctype", "proc") or "proc" ).title() # convert to LAL lals...
"""Write data to a GWF file using the LALFrame API """ if not start: start = list(tsdict.values())[0].xspan[0] if not end: end = list(tsdict.values())[0].xspan[1] duration = end - start # get ifos list detectors = 0 _detidx = list(lalutils.LAL_DETECTORS.keys()) for serie...
identifier_body
lalframe.py
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
The frame format is defined in LIGO-T970130 available from dcc.ligo.org. """ import os.path import warnings # import in this order so that lalframe throws the ImportError # to give the user a bit more information import lalframe import lal from ....io.cache import is_cache from ....io.utils import (file_list, file_...
random_line_split
lalframe.py
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2014-2020) # # This file is part of GWpy. # # GWpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
start = max(epoch, lalutils.to_lal_ligotimegps(start)) if end is None: end = epoch + streamdur duration = float(end - start) # read data out = series_class.DictClass() for name in channels: out[name] = series_class.from_lal( _read_channel(stream, str(name), start=st...
start = epoch
conditional_block
underscore-mixin.js
_.mixin({ on : function(obj, event, callback) { // Define a global Observer
} if(this.isUndefined(obj._events)) obj._events = {}; if (!(event in obj._events)) obj._events[event] = []; obj._events[event].push(callback); return this; }, once : function(obj, event, callback) { if(this.isString(obj)) { callback = event; event = obj; obj = this; } var removeEvent = function() { _.remove...
if(this.isString(obj)) { callback = event; event = obj; obj = this;
random_line_split
Device.d.ts
import { DeviceType } from './Device.types'; export { DeviceType }; export declare const isDevice: boolean; export declare const brand: string | null; export declare const manufacturer: string | null; export declare const modelId: any; export declare const modelName: string | null; export declare const designName: stri...
//# sourceMappingURL=Device.d.ts.map
export declare function getPlatformFeaturesAsync(): Promise<string[]>; export declare function hasPlatformFeatureAsync(feature: string): Promise<boolean>;
random_line_split
lib.rs
//! [tui](https://github.com/fdehau/tui-rs) is a library used to build rich //! terminal users interfaces and dashboards. //! //! ![](https://raw.githubusercontent.com/fdehau/tui-rs/master/assets/demo.gif) //! //! # Get started //! //! ## Adding `tui` as a dependency //! //! ```toml //! [dependencies] //! tui = "0.17" ...
//! //! The same logic applies for all other available backends. //! //! ## Creating a `Terminal` //! //! Every application using `tui` should start by instantiating a `Terminal`. It is a light //! abstraction over available backends that provides basic functionalities such as clearing the //! screen, hiding the cursor...
//! //! ```
random_line_split
webpack.prod.config.js
const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const path = require('path'); const mainPath = path.resolve('./src'); const buildPath = path.resolve('./dist'); module.exports = { entry: [ 'bootstrap-loader', mainPath, ], output: { filename: 'bundl...
module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader'], }, { test: /\.css$/, loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader' }), }, { test: /\.scss$/, ...
},
random_line_split
markdown_checklist.py
#Library avaiable here: https://github.com/FND/markdown-checklist import re from markdown.extensions import Extension from markdown.preprocessors import Preprocessor from markdown.postprocessors import Postprocessor def
(configs=[]): return ChecklistExtension(configs=configs) class ChecklistExtension(Extension): def extendMarkdown(self, md, md_globals): md.postprocessors.add('checklist', ChecklistPostprocessor(md), '>raw_html') class ChecklistPostprocessor(Postprocessor): """ adds checklist...
makeExtension
identifier_name
markdown_checklist.py
#Library avaiable here: https://github.com/FND/markdown-checklist import re from markdown.extensions import Extension from markdown.preprocessors import Preprocessor from markdown.postprocessors import Postprocessor def makeExtension(configs=[]): return ChecklistExtension(configs=configs) class ChecklistExten...
class ChecklistPostprocessor(Postprocessor): """ adds checklist class to list element """ pattern = re.compile(r'<li>\[([ Xx])\]') def run(self, html): html = re.sub(self.pattern, self._convert_checkbox, html) before = '<ul>\n<li><input type="checkbox"' after = before.re...
def extendMarkdown(self, md, md_globals): md.postprocessors.add('checklist', ChecklistPostprocessor(md), '>raw_html')
identifier_body
markdown_checklist.py
#Library avaiable here: https://github.com/FND/markdown-checklist import re from markdown.extensions import Extension from markdown.preprocessors import Preprocessor from markdown.postprocessors import Postprocessor def makeExtension(configs=[]): return ChecklistExtension(configs=configs) class ChecklistExten...
return '<li><input type="checkbox" disabled%s>' % checked
random_line_split
basic_definitions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(f): return f @basic_decorator @basic_decorator def decorated_function(x): if x > 0: return 1 return 2
basic_decorator
identifier_name
basic_definitions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
simple_lambda = lambda: None class SimpleClass(object): def simple_method(self): return self def method_with_print(self): print('foo') def function_with_multiline_call(x): """Docstring.""" return range( x, x + 1, ) def basic_decorator(f): return f @basic_decorator @basic_dec...
print('foo')
identifier_body
basic_definitions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
return 2
return 1
conditional_block
basic_definitions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
#
random_line_split
elasticSearchCall.js
var events = require('events'), http = require('http'), https = require('https'), util = require('util'); module.exports = ElasticSearchCall; function
(params, options, cb) { var self = this self.host = options.host || 'localhost'; self.port = options.port || 80; self.secure = options.secure || false; self.defaultMethod = options.defaultMethod || 'GET'; self.auth = options.auth || false; self.params = params || {}; self.path = [ option...
ElasticSearchCall
identifier_name
elasticSearchCall.js
var events = require('events'), http = require('http'), https = require('https'), util = require('util'); module.exports = ElasticSearchCall; function ElasticSearchCall(params, options, cb) { var self = this self.host = options.host || 'localhost'; self.port = options.port || 80; self.secu...
response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { if (typeof self.callback == 'function') { self.callback(undefined, body); } else { self.emit("data", body); self.emit("do...
request.on('response', function (response) { var body = "";
random_line_split
elasticSearchCall.js
var events = require('events'), http = require('http'), https = require('https'), util = require('util'); module.exports = ElasticSearchCall; function ElasticSearchCall(params, options, cb) { var self = this self.host = options.host || 'localhost'; self.port = options.port || 80; self.secu...
request.on('error', function (error) { self.emit("error", error) }) request.on('response', function (response) { var body = ""; response.on('data', function (chunk) { body += chunk; }); response.on('end', function () { if (typeof self.callba...
{ request.setTimeout(self.timeout, function () { self.emit('error', new Error('timed out after ' + self.timeout + 'ms')); }); }
conditional_block
elasticSearchCall.js
var events = require('events'), http = require('http'), https = require('https'), util = require('util'); module.exports = ElasticSearchCall; function ElasticSearchCall(params, options, cb)
util.inherits(ElasticSearchCall, events.EventEmitter); ElasticSearchCall.prototype.exec = function (cb) { var self = this var reqOptions = { path:this.path + this.params.path, method:this.params.method || this.defaultMethod, host:this.host, port:this.port, agent: this....
{ var self = this self.host = options.host || 'localhost'; self.port = options.port || 80; self.secure = options.secure || false; self.defaultMethod = options.defaultMethod || 'GET'; self.auth = options.auth || false; self.params = params || {}; self.path = [ options.pathPrefix || '', op...
identifier_body
INotificationView.ts
/** * Defines what the `{get} /api/notification/` aka `getNotifications` route returns as response (in form of an array). * It is the sanitized version of `INotification` interface: The property names are identical, but `changedCourse`, * `changedLecture` and `changedUnit` only represent the optional IDs (`_id`s) of...
}
changedCourse?: string; changedLecture?: string; changedUnit?: string; text: string; isOld: boolean;
random_line_split
orgUserServiceTest.js
/** * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ...
expect(callbackSpied.called).to.be.true; })); });
orgUserServiceSUT.addUser(user).then(callbackSpied); $httpBackend.flush();
random_line_split
decafmud.telopt.gmcp.js
/*! * DecafMUD v0.9.0 * http://decafmud.stendec.me * * Copyright 2010, Stendec <stendec365@gmail.com> */ /** * @fileOverview DecafMUD TELOPT Handler: GMCP * @author Stendec <stendec365@gmail.com> * @version 0.9.0 */ (function(DecafMUD) { // Shortcut the TELNET constants for ease of use. var ...
this.sendGMCP("Core.Ping", avg); this.pingWhen = new Date(); // Schedule a new ping. var g = this; this.pingTimer = setTimeout(function(){g.ping();}, this.pingDelay*1000); } /** Handle an incoming GMCP message. */ GMCP.prototype._sb = function(data) { // Find the end of the package. var ind = data...
avg = this.pingAverage; }
conditional_block
decafmud.telopt.gmcp.js
/*! * DecafMUD v0.9.0 * http://decafmud.stendec.me * * Copyright 2010, Stendec <stendec365@gmail.com> */ /** * @fileOverview DecafMUD TELOPT Handler: GMCP * @author Stendec <stendec365@gmail.com> * @version 0.9.0 */ (function(DecafMUD) { // Shortcut the TELNET constants for ease of use. var ...
if ( pckg.length === 0 ) { return; } // Debug it. if ( out !== undefined && 'console' in window && console.groupCollapsed ) { console.groupCollapsed('DecafMUD['+this.decaf.id+'] RCVD IAC SB GMCP "'+pckg+'" ... IAC SE'); console.dir(out); console.groupEnd('DecafMUD['+this.decaf.id+'] RCVD IAC SB GMCP "'...
// If there's no package, return.
random_line_split
file_dlg.rs
/* Copyright 2015 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ use super::control_prelude::*; use std::borrow::Cow; use std::ffi::CStr; use std::path::{PathBuf, Path}; ...
() -> FileDlg { unsafe { ::iup_open(); let ih = IupFileDlg(); FileDlg(HandleRc::new(ih)) } } pub fn dialog_type(&self) -> FileDialogType { unsafe { let val = get_str_attribute_slice(self.handle(), "DIALOGTYPE\0"); FileDialogTyp...
new
identifier_name
file_dlg.rs
/* Copyright 2015 Jordan Miner * * Licensed under the MIT license <LICENSE or * http://opensource.org/licenses/MIT>. This file may not be copied, * modified, or distributed except according to those terms. */ use super::control_prelude::*; use std::borrow::Cow; use std::ffi::CStr; use std::path::{PathBuf, Path}; ...
} } pub fn value_multiple(&self) -> Option<Vec<PathBuf>> { assert!(self.multiple_files()); unsafe { let val = get_attribute_ptr(self.handle(), "VALUE\0"); if val.is_null() { None } else { const PIPE: &'static [char] = &...
None } else { Some(PathBuf::from(&*CStr::from_ptr(val).to_string_lossy())) }
random_line_split
remove-dups.py
# remove duplicates of linked list class Node(object): # define constructor def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def add(self, new_node): current_node = self.head if self.head: while current_node.next: ...
def remove(self, data): current_node = self.head previous = None while current_node.data != data and current_node.next: # move through linked list until you hit node you want to delete previous = current_node current_node = current_node.next if current_node.data == data: if previous: previous.ne...
counter = 1 current_node = self.head if position < 1: return None while current_node and counter <= position: # go through linked list until you reach input position if counter == position: return current_node current_node = current_node.next counter += 1 return None # if position is larger than...
identifier_body
remove-dups.py
# remove duplicates of linked list class Node(object): # define constructor def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def add(self, new_node): current_node = self.head if self.head: while current_node.next: ...
(self, position): counter = 1 current_node = self.head if position < 1: return None while current_node and counter <= position: # go through linked list until you reach input position if counter == position: return current_node current_node = current_node.next counter += 1 return None # if pos...
search
identifier_name
remove-dups.py
# remove duplicates of linked list class Node(object): # define constructor def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def add(self, new_node): current_node = self.head if self.head: while current_node.next: ...
if counter == position: return current_node current_node = current_node.next counter += 1 return None # if position is larger than length of linked list def remove(self, data): current_node = self.head previous = None while current_node.data != data and current_node.next: # move through linked li...
return None while current_node and counter <= position: # go through linked list until you reach input position
random_line_split
remove-dups.py
# remove duplicates of linked list class Node(object): # define constructor def __init__(self, data): self.data = data self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def add(self, new_node): current_node = self.head if self.head: while current_node.next: ...
else: dups[next_node.data] = True current_node = next_node next_node = next_node.next # test cases node_one = Node(1) node_two = Node(2) node_three = Node(3) node_four = Node(4) node_five = Node(1) node_six = Node(2) test_one = LinkedList(node_one) test_one.add(node_two) test_one.add(node_three) test_o...
current_node.next = next_node.next
conditional_block
c_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt from frappe import _ from frappe.model.document import Document
for d in self.get('invoice_details'): if d.invoice_no: inv = frappe.db.sql("""select c_form_applicable, c_form_no from `tabSales Invoice` where name = %s and docstatus = 1""", d.invoice_no) if inv and inv[0][0] != 'Yes': frappe.throw("C-form is not applicable for Invoice: %s" % d.invoice_no) ...
class CForm(Document): def validate(self): """Validate invoice that c-form is applicable and no other c-form is received for that"""
random_line_split
c_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt from frappe import _ from frappe.model.document import Document class CForm(Document): def validate(self...
(self): total = sum([flt(d.grand_total) for d in self.get('invoice_details')]) frappe.db.set(self, 'total_invoiced_amount', total) def get_invoice_details(self, invoice_no): """ Pull details from invoices for referrence """ if invoice_no: inv = frappe.db.get_value("Sales Invoice", invoice_no, ["posting...
set_total_invoiced_amount
identifier_name
c_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt from frappe import _ from frappe.model.document import Document class CForm(Document): def validate(self...
""" Pull details from invoices for referrence """ if invoice_no: inv = frappe.db.get_value("Sales Invoice", invoice_no, ["posting_date", "territory", "net_total", "grand_total"], as_dict=True) return { 'invoice_date' : inv.posting_date, 'territory' : inv.territory, 'net_total' : inv.net_to...
identifier_body
c_form.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt from frappe import _ from frappe.model.document import Document class CForm(Document): def validate(self...
else: frappe.throw(_("Please enter atleast 1 invoice in the table")) def set_total_invoiced_amount(self): total = sum([flt(d.grand_total) for d in self.get('invoice_details')]) frappe.db.set(self, 'total_invoiced_amount', total) def get_invoice_details(self, invoice_no): """ Pull details from invoices f...
frappe.db.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s where name in (%s)""" % ('%s', '%s', ', '.join(['%s'] * len(inv))), tuple([self.name, self.modified] + inv)) frappe.db.sql("""update `tabSales Invoice` set c_form_no = null, modified = %s where name not in (%s) and ifnull(c_form_no, ''...
conditional_block
msgsend-ring-mutex-arcs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn init() -> (pipe,pipe) { let m = Arc::new((Mutex::new(Vec::new()), Condvar::new())); ((&m).clone(), m) } fn thread_ring(i: usize, count: usize, num_chan: pipe, num_port: pipe) { let mut num_chan = Some(num_chan); let mut num_port = Some(num_port); // Send/Receive lots of messages. for j in...
{ let &(ref lock, ref cond) = &**p; let mut arr = lock.lock().unwrap(); while arr.is_empty() { arr = cond.wait(arr).unwrap(); } arr.pop().unwrap() }
identifier_body
msgsend-ring-mutex-arcs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(i: usize, count: usize, num_chan: pipe, num_port: pipe) { let mut num_chan = Some(num_chan); let mut num_port = Some(num_port); // Send/Receive lots of messages. for j in 0..count { //println!("thread %?, iter %?", i, j); let num_chan2 = num_chan.take().unwrap(); let num_port2 =...
thread_ring
identifier_name
msgsend-ring-mutex-arcs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// all done, report stats. let num_msgs = num_tasks * msg_per_task; let rate = (num_msgs as f64) / (dur.as_secs() as f64); println!("Sent {} messages in {:?}", num_msgs, dur); println!(" {} messages / second", rate); println!(" {} μs / message", 1000000. / rate); }
});
random_line_split
test-viewer-initiated-handshake.js
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
const ampDocUrl = `${loc.protocol}//iframe.${loc.hostname}:${loc.port}${ampDocSrc}`; viewerEl = document.createElement('div'); document.body.appendChild(viewerEl); viewer = new WebviewViewerForTesting(viewerEl, '1', ampDocUrl, true); }); afterEach(() => { document.body.removeChil...
beforeEach(() => { const loc = window.location;
random_line_split