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
data.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
// Quirks-mode matches are case-insensitive. let public = opt_to_ascii_lower(public); let system = opt_to_ascii_lower(system); let quirk = match (opt_as_slice(&public), opt_as_slice(&system)) { _ if doctype.force_quirks => Quirks, _ if name != Some("html") => Quirks, _ if ifr...
{ haystack.iter().any(|&x| needle.starts_with(x)) }
identifier_body
www.ts
#!/usr/bin/env node /** * Module dependencies. */ import { app } from '../app'; import { SERVER_PORT } from '../config'; import * as http from 'http'; /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || SERVER_PORT); app.set('port', port); /** * Create HTTP s...
* Event listener for HTTP server 'error' event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES...
return false; } /**
random_line_split
www.ts
#!/usr/bin/env node /** * Module dependencies. */ import { app } from '../app'; import { SERVER_PORT } from '../config'; import * as http from 'http'; /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || SERVER_PORT); app.set('port', port); /** * Create HTTP s...
return false; } /** * Event listener for HTTP server 'error' event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error...
{ // port number return normalizedPort; }
conditional_block
www.ts
#!/usr/bin/env node /** * Module dependencies. */ import { app } from '../app'; import { SERVER_PORT } from '../config'; import * as http from 'http'; /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || SERVER_PORT); app.set('port', port); /** * Create HTTP s...
(val): boolean | number { const normalizedPort = parseInt(val, 10); if (isNaN(normalizedPort)) { // named pipe return val; } if (normalizedPort >= 0) { // port number return normalizedPort; } return false; } /** * Event listener for HTTP server 'error' event. */ function onError(erro...
normalizePort
identifier_name
www.ts
#!/usr/bin/env node /** * Module dependencies. */ import { app } from '../app'; import { SERVER_PORT } from '../config'; import * as http from 'http'; /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || SERVER_PORT); app.set('port', port); /** * Create HTTP s...
{ const addr = server.address(); const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; console.log('Listening on ' + bind); }
identifier_body
raw_block.rs
use Renderable; use context::Context; use LiquidOptions; use token::Token; use lexer::Element::{self, Expression, Tag, Raw}; use error::Result; struct RawT { content: String, } impl Renderable for RawT { fn
(&self, _context: &mut Context) -> Result<Option<String>> { Ok(Some(self.content.to_owned())) } } pub fn raw_block(_tag_name: &str, _arguments: &[Token], tokens: &[Element], _options: &LiquidOptions) -> Result<Box<Renderable>> { let co...
render
identifier_name
raw_block.rs
use Renderable; use context::Context; use LiquidOptions; use token::Token; use lexer::Element::{self, Expression, Tag, Raw}; use error::Result; struct RawT { content: String, } impl Renderable for RawT { fn render(&self, _context: &mut Context) -> Result<Option<String>>
} pub fn raw_block(_tag_name: &str, _arguments: &[Token], tokens: &[Element], _options: &LiquidOptions) -> Result<Box<Renderable>> { let content = tokens.iter().fold("".to_owned(), |a, b| { match *b { Expression(_, ref text) |...
{ Ok(Some(self.content.to_owned())) }
identifier_body
raw_block.rs
use Renderable; use context::Context; use LiquidOptions; use token::Token; use lexer::Element::{self, Expression, Tag, Raw}; use error::Result; struct RawT { content: String,
impl Renderable for RawT { fn render(&self, _context: &mut Context) -> Result<Option<String>> { Ok(Some(self.content.to_owned())) } } pub fn raw_block(_tag_name: &str, _arguments: &[Token], tokens: &[Element], _options: &LiquidOptions) ...
}
random_line_split
local-generic.rs
// We specify -C incremental here because we want to test the partitioning for // incremental compilation // compile-flags:-Zprint-mono-items=eager -Cincremental=tmp/partitioning-tests/local-generic #![allow(dead_code)] #![crate_type="lib"] //~ MONO_ITEM fn generic::<u32> @@ local_generic.volatile[External] //~ MONO_...
() { let _ = generic("abc"); } }
user
identifier_name
local-generic.rs
// We specify -C incremental here because we want to test the partitioning for // incremental compilation // compile-flags:-Zprint-mono-items=eager -Cincremental=tmp/partitioning-tests/local-generic #![allow(dead_code)] #![crate_type="lib"] //~ MONO_ITEM fn generic::<u32> @@ local_generic.volatile[External] //~ MONO_...
mod mod1 { pub use super::generic; //~ MONO_ITEM fn mod1::user @@ local_generic-mod1[Internal] fn user() { let _ = generic(0u64); } mod mod1 { use super::generic; //~ MONO_ITEM fn mod1::mod1::user @@ local_generic-mod1-mod1[Internal] fn user() { let _...
{ let _ = generic(0u32); }
identifier_body
local-generic.rs
// We specify -C incremental here because we want to test the partitioning for // incremental compilation // compile-flags:-Zprint-mono-items=eager -Cincremental=tmp/partitioning-tests/local-generic #![allow(dead_code)] #![crate_type="lib"] //~ MONO_ITEM fn generic::<u32> @@ local_generic.volatile[External] //~ MONO_...
fn user() { let _ = generic(0u32); } mod mod1 { pub use super::generic; //~ MONO_ITEM fn mod1::user @@ local_generic-mod1[Internal] fn user() { let _ = generic(0u64); } mod mod1 { use super::generic; //~ MONO_ITEM fn mod1::mod1::user @@ local_generic-mod1-mod1[Interna...
//~ MONO_ITEM fn generic::<char> @@ local_generic.volatile[External] //~ MONO_ITEM fn generic::<&str> @@ local_generic.volatile[External] pub fn generic<T>(x: T) -> T { x } //~ MONO_ITEM fn user @@ local_generic[Internal]
random_line_split
error.rs
use std::error; use std::fmt; use std::io::{self, Error}; #[derive(Debug)] pub struct TarError { desc: String, io: io::Error, } impl TarError { pub fn new(desc: &str, err: Error) -> TarError { TarError { desc: desc.to_string(), io: err, } } } impl error::Error ...
}
random_line_split
error.rs
use std::error; use std::fmt; use std::io::{self, Error}; #[derive(Debug)] pub struct TarError { desc: String, io: io::Error, } impl TarError { pub fn new(desc: &str, err: Error) -> TarError { TarError { desc: desc.to_string(), io: err, } } } impl error::Error ...
} impl fmt::Display for TarError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.desc.fmt(f) } } impl From<TarError> for Error { fn from(t: TarError) -> Error { Error::new(t.io.kind(), t) } }
{ Some(&self.io) }
identifier_body
error.rs
use std::error; use std::fmt; use std::io::{self, Error}; #[derive(Debug)] pub struct
{ desc: String, io: io::Error, } impl TarError { pub fn new(desc: &str, err: Error) -> TarError { TarError { desc: desc.to_string(), io: err, } } } impl error::Error for TarError { fn description(&self) -> &str { &self.desc } fn cause(&self...
TarError
identifier_name
slack_webhook_hook.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook # noqa warnings.warn( "This module is deprecated. Please use `airflow.providers.slack.hooks.slack_webhook`.", DeprecationWarning, stacklevel=2 )
# pylint: disable=unused-import
random_line_split
aiplatform_v1_generated_vizier_service_delete_study_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-aiplatform # [START aiplatform_v1_generated_VizierService_DeleteStudy_sync] from google.cloud import aiplatform_v1 def sample_delete_study...
# # Generated code. DO NOT EDIT! # # Snippet for DeleteStudy # NOTE: This snippet has been automatically generated for illustrative purposes only.
random_line_split
aiplatform_v1_generated_vizier_service_delete_study_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
(): # Create a client client = aiplatform_v1.VizierServiceClient() # Initialize request argument(s) request = aiplatform_v1.DeleteStudyRequest( name="name_value", ) # Make the request client.delete_study(request=request) # [END aiplatform_v1_generated_VizierService_DeleteStudy_sy...
sample_delete_study
identifier_name
aiplatform_v1_generated_vizier_service_delete_study_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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...
# [END aiplatform_v1_generated_VizierService_DeleteStudy_sync]
client = aiplatform_v1.VizierServiceClient() # Initialize request argument(s) request = aiplatform_v1.DeleteStudyRequest( name="name_value", ) # Make the request client.delete_study(request=request)
identifier_body
XMLHandler.js
<<<<<<< HEAD var xmlDoc; var xmlloaded = false; var _finalUrl; /* * input: none * output: none * gets zipcode from the zipcode text field */ function createURL() { var zip = document.getElementById("zipcode").value; var format = "&format=xml" var _clientId = "&client_id=API KEY"; var _url = "https:...
{ var i, buyTickets; var xmlDoc = xml.responseXML; var x = xmlDoc.getElementsByTagName("recommendations"); for (i = 0; i < x.length; i++) { buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue; } document.getElementById("demo").innerHTML = window.open(buyTickets); }
identifier_body
XMLHandler.js
<<<<<<< HEAD var xmlDoc; var xmlloaded = false; var _finalUrl; /* * input: none * output: none * gets zipcode from the zipcode text field */ function createURL() { var zip = document.getElementById("zipcode").value; var format = "&format=xml" var _clientId = "&client_id=API KEY"; var _url = "https:...
() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { // ready states 1-4 & status 200 = okay // 0: uninitialized // 1: loading // 2: loaded // 3: interactive // 4: complete if (xhttp.readyState == 4 && xhttp.status == 200) { ...
loadDoc
identifier_name
XMLHandler.js
<<<<<<< HEAD var xmlDoc; var xmlloaded = false; var _finalUrl; /* * input: none * output: none * gets zipcode from the zipcode text field */ function createURL() { var zip = document.getElementById("zipcode").value; var format = "&format=xml" var _clientId = "&client_id=API KEY"; var _url = "https:...
document.getElementById("demo").innerHTML = window.open(buyTickets); }
{ buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue; }
conditional_block
XMLHandler.js
var xmlloaded = false; var _finalUrl; /* * input: none * output: none * gets zipcode from the zipcode text field */ function createURL() { var zip = document.getElementById("zipcode").value; var format = "&format=xml" var _clientId = "&client_id=API KEY"; var _url = "https://api.seatgeek.com/2/reco...
<<<<<<< HEAD var xmlDoc;
random_line_split
televigo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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) a...
def procesarDescarga(self): ''' Procesa lo necesario para obtener la url final del vídeo a descargar y devuelve esta y el nombre como se quiere que se descarge el archivo de la siguiente forma: return [ruta_url, nombre] Si no se quiere especificar un nombre p...
Clase que maneja la descarga los vídeos de TeleVigo ''' URL_TeleVigo = "http://www.televigo.com/" def __init__(self, url=""): self._URL_recibida = url def getURL(self): return self._URL_recibida def setURL(self, url): self._URL_recibida = url url = property...
identifier_body
televigo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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) a...
urn [url, name]
earNombre(name) ret
conditional_block
televigo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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) a...
, url): self._URL_recibida = url url = property(getURL, setURL) # Funciones privadas que ayuden a procesarDescarga(self): def __descHTML(self, url2down): ''' Método que utiliza la clase descargar para descargar el HTML ''' D = Descargar(url2down) return D.descargar() de...
L(self
identifier_name
televigo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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) a...
__date__ ="$15-may-2011 11:03:38$" from Descargar import Descargar from utiles import salir, formatearNombre, printt import sys class TeleVigo(object): ''' Clase que maneja la descarga los vídeos de TeleVigo ''' URL_TeleVigo = "http://www.televigo.com/" def __init__(self, url=""): ...
# Pequeña descripción de qué canal de tv es el módulo __author__="aabilio"
random_line_split
DDTElement.ts
/// <reference path='../ddt.ts' /> import ddt = require('../ddt'); import chai = require('chai'); describe('DDTElement', function() { var expect = chai.expect; var DDTElement = ddt.DDTElement; describe('#getNode()', function() {
expect(dEl.getNode()).to.equal(el); }); }); describe('#offsetTop()', function() { it('should return the top offset of an element', function() { var $el = $(document.createElement('div')) .css({ top : 10, left : 5, ...
it('should return the node it represents', function() { var el = document.createElement('p'); var $el = $(el); var dEl = new DDTElement($el);
random_line_split
Gruntfile.js
// BEGIN Gruntfile // this file configures the behavior of Grunt and its installed task modules (this is currently setup for a WordPress project running Bones theme) module.exports = function(grunt) { // wrapper function - encapsulates your Grunt configuration var globalConfig = { // set variable for project url
src: '/var/www/vhosts/jhqp/wp-content/themes/eddiemachado-bones-evolvingwisdom', // change this url! dest: '/var/www/vhosts/jhqp/wp-content/themes/eddiemachado-bones-evolvingwisdom' // change this url! }; grunt.initConfig({ // initialize the Grunt configuration object globalConfig: glob...
random_line_split
htmltableheadercellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding; use dom::bindings::codegen::InheritTypes:...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLTableHeaderCellElement> { let element = HTMLTableHeaderCellElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLTableHeaderCellElementBinding::Wr...
new
identifier_name
htmltableheadercellelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding; use dom::bindings::codegen::InheritTypes:...
use dom::eventtarget::{EventTarget, EventTargetTypeId}; use dom::htmlelement::HTMLElementTypeId; use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementTypeId}; use dom::node::{Node, NodeTypeId}; use util::str::DOMString; #[dom_struct] pub struct HTMLTableHeaderCellElement { htmltablecellelement...
random_line_split
component-tester.d.ts
import { Aurelia, FrameworkConfiguration } from 'aurelia-framework'; export declare class StageComponent { static withResources<T = any>(resources?: string | string[]): ComponentTester<T>; } export declare class
<T = any> { bind: (bindingContext: {}) => Promise<void>; attached: () => Promise<void>; detached: () => Promise<void>; unbind: () => Promise<void>; element: Element; viewModel: T; private html; private resources; private bindingContext; private rootView; private host; con...
ComponentTester
identifier_name
component-tester.d.ts
import { Aurelia, FrameworkConfiguration } from 'aurelia-framework'; export declare class StageComponent { static withResources<T = any>(resources?: string | string[]): ComponentTester<T>; } export declare class ComponentTester<T = any> { bind: (bindingContext: {}) => Promise<void>; attached: () => Promise<...
}
timeout?: number; }): Promise<NodeListOf<Element>>;
random_line_split
_cusum.py
# -*- coding: utf-8 -*- """ Methods for estimating structural breaks in time series regressions TODO: extract and move Chow test from "commission test" over to here """ from __future__ import division from collections import namedtuple import logging import numpy as np import pandas as pd from scipy.optimize import ...
return 1 - (1 - p) ** k def _cusum_rec_test_crit(alpha): """ Return critical test statistic value for some alpha """ return brentq(lambda _x: _brownian_motion_pvalue(_x, 1) - alpha, 0, 20) @try_jit(nopython=True, nogil=True) def _cusum_rec_boundary(x, alpha=0.05): """ Equivalent to ``strucchange::b...
= 2 * (1 - pnorm(3 * x) + np.exp(-4 * x ** 2) * (pnorm(x) + pnorm(5 * x) - 1) - np.exp(-16 * x ** 2) * (1 - pnorm(x)))
conditional_block
_cusum.py
# -*- coding: utf-8 -*- """ Methods for estimating structural breaks in time series regressions TODO: extract and move Chow test from "commission test" over to here """ from __future__ import division from collections import namedtuple import logging import numpy as np import pandas as pd from scipy.optimize import ...
process = pd.Series(data=process, index=index, name='REC-CUSUM') boundary = pd.Series(data=boundary, index=index, name='Boundary') return StructuralBreakResult(method='REC-CUSUM', process=process, boundary=boundary, ...
random_line_split
_cusum.py
# -*- coding: utf-8 -*- """ Methods for estimating structural breaks in time series regressions TODO: extract and move Chow test from "commission test" over to here """ from __future__ import division from collections import namedtuple import logging import numpy as np import pandas as pd from scipy.optimize import ...
(resid, ddof): n = resid.size df = n - ddof sigma = ((resid ** 2).sum() / df * n) ** 0.5 process = resid.cumsum() / sigma return process @try_jit(nopython=True, nogil=True) def _cusum_OLS(X, y): n, p = X.shape beta = np.linalg.lstsq(X, y)[0] resid = np.dot(X, beta) - y process = ...
_cusum
identifier_name
_cusum.py
# -*- coding: utf-8 -*- """ Methods for estimating structural breaks in time series regressions TODO: extract and move Chow test from "commission test" over to here """ from __future__ import division from collections import namedtuple import logging import numpy as np import pandas as pd from scipy.optimize import ...
@try_jit(nopython=True, nogil=True) def _cusum_OLS(X, y): n, p = X.shape beta = np.linalg.lstsq(X, y)[0] resid = np.dot(X, beta) - y process = _cusum(resid, p) _process = np.abs(process) idx = _process.argmax() score = _process[idx] return process, score, idx def cusum_OLS(X, y, a...
n = resid.size df = n - ddof sigma = ((resid ** 2).sum() / df * n) ** 0.5 process = resid.cumsum() / sigma return process
identifier_body
puput_initial_data.py
# -*- coding: utf-8 -*- from django import VERSION as DJANGO_VERSION from django.contrib.contenttypes.models import ContentType from django.core.management import BaseCommand from wagtail.wagtailcore.models import Page, Site class Command(BaseCommand): help = "Load Puput initial dummy data" def
(self, *args, **options): # Get blogpage content type blogpage_content_type, created = ContentType.objects.get_or_create( model='blogpage', app_label='puput', defaults={'name': 'page'} if DJANGO_VERSION < (1, 8) else {} ) # Get root page rootp...
handle
identifier_name
puput_initial_data.py
# -*- coding: utf-8 -*- from django import VERSION as DJANGO_VERSION from django.contrib.contenttypes.models import ContentType from django.core.management import BaseCommand from wagtail.wagtailcore.models import Page, Site class Command(BaseCommand):
title="Blog", content_type=blogpage_content_type, slug='blog', ) # Add blog page as a child for homepage rootpage.add_child(instance=blogpage) revision = blogpage.save_revision() revision.publish()
help = "Load Puput initial dummy data" def handle(self, *args, **options): # Get blogpage content type blogpage_content_type, created = ContentType.objects.get_or_create( model='blogpage', app_label='puput', defaults={'name': 'page'} if DJANGO_VERSION < (1, 8) el...
identifier_body
puput_initial_data.py
# -*- coding: utf-8 -*- from django import VERSION as DJANGO_VERSION from django.contrib.contenttypes.models import ContentType
class Command(BaseCommand): help = "Load Puput initial dummy data" def handle(self, *args, **options): # Get blogpage content type blogpage_content_type, created = ContentType.objects.get_or_create( model='blogpage', app_label='puput', defaults={'name': 'pa...
from django.core.management import BaseCommand from wagtail.wagtailcore.models import Page, Site
random_line_split
composite_shape_against_any.rs
use std::marker::PhantomData; use na::{Identity, Translate, Translation}; use na; use entities::bounding_volume::{HasAABB, AABB}; use entities::partitioning::BVTCostFn; use entities::shape::CompositeShape; use entities::inspection::Repr; use point::PointQuery; use geometry::distance_internal; use math::{Scalar, Point, ...
(&mut self, bv: &AABB<P>) -> Option<<P::Vect as Vect>::Scalar> { // Compute the minkowski sum of the two AABBs. let msum = AABB::new(*bv.mins() + self.msum_shift + (-self.msum_margin), *bv.maxs() + self.msum_shift + self.msum_margin); // Compute the distance to the ...
compute_bv_cost
identifier_name
composite_shape_against_any.rs
use std::marker::PhantomData; use na::{Identity, Translate, Translation}; use na; use entities::bounding_volume::{HasAABB, AABB}; use entities::partitioning::BVTCostFn; use entities::shape::CompositeShape; use entities::inspection::Repr; use point::PointQuery; use geometry::distance_internal; use math::{Scalar, Point, ...
} impl<'a, P, M, G1: ?Sized, G2: ?Sized> BVTCostFn<<P::Vect as Vect>::Scalar, usize, AABB<P>, <P::Vect as Vect>::Scalar> for CompositeShapeAgainstAnyDistCostFn<'a, P, M, G1, G2> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> + Translation<P::Vect>, G1: CompositeShap...
{ let ls_m2 = na::inv(m1).expect("The transformation `m1` must be inversible.") * *m2; let ls_aabb2 = g2.aabb(&ls_m2); CompositeShapeAgainstAnyDistCostFn { msum_shift: -ls_aabb2.center().to_vec(), msum_margin: ls_aabb2.half_extents(), m1: m1, ...
identifier_body
composite_shape_against_any.rs
use std::marker::PhantomData; use na::{Identity, Translate, Translation}; use na; use entities::bounding_volume::{HasAABB, AABB}; use entities::partitioning::BVTCostFn; use entities::shape::CompositeShape; use entities::inspection::Repr; use point::PointQuery; use geometry::distance_internal; use math::{Scalar, Point, ...
g1.bvt().best_first_search(&mut cost_fn).map(|(_, res)| res).expect("The composite shape must not be empty.") } /// Smallest distance between a shape and a composite shape. pub fn any_against_composite_shape<P, M, G1: ?Sized, G2: ?Sized>(m1: &M, g1: &G1, m2: &M, g2: &G2) -> <P::Vect as Vect>::Scalar where P: ...
random_line_split
issue-5100.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
enum A { B, C } fn main() { match (true, false) { B => (), //~ ERROR expected `(bool,bool)` but found an enum or structure pattern _ => () } match (true, false) { (true, false, false) => () //~ ERROR mismatched types: expected `(bool,bool)` but found tuple (expected a tuple with 2...
// 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. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
issue-5100.rs
// Copyright 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-MIT or ...
() { match (true, false) { B => (), //~ ERROR expected `(bool,bool)` but found an enum or structure pattern _ => () } match (true, false) { (true, false, false) => () //~ ERROR mismatched types: expected `(bool,bool)` but found tuple (expected a tuple with 2 elements but found one w...
main
identifier_name
AABB.ts
import Vector2d from "../math/vector2d"; // Axis Aligned Bounding Box export default class BoundingBox { public static overlaps(boxA: BoundingBox, boxB: BoundingBox): boolean { return ( Vector2d.isLessOrEqual(boxA.bound.min, boxB.bound.max) && Vector2d.isLessOrEqual(boxB.bound.min, boxA.bound.max) ); } ...
public draw(context) { context.save(); context.translate(this.bound.min.getX(), this.bound.min.getY()); context.beginPath(); context.rect(0, 0, this.bound.max.getX() - this.bound.min.getX(), this.bound.max.getY() - this.bound.min.getY()); context.lineWidth = 0.5; context.strokeStyle = "#00ff00"; contex...
{ let max = this.bound.max; let min = this.bound.min; if (Vector2d.isGreater(max, box.bound.max)) { max = box.bound.max; } if (Vector2d.isLess(min, box.bound.min)) { min = box.bound.min; } }
identifier_body
AABB.ts
import Vector2d from "../math/vector2d"; // Axis Aligned Bounding Box export default class BoundingBox { public static overlaps(boxA: BoundingBox, boxB: BoundingBox): boolean { return ( Vector2d.isLessOrEqual(boxA.bound.min, boxB.bound.max) && Vector2d.isLessOrEqual(boxB.bound.min, boxA.bound.max) ); } ...
} if (Vector2d.isLess(min, box.bound.min)) { min = box.bound.min; } } public draw(context) { context.save(); context.translate(this.bound.min.getX(), this.bound.min.getY()); context.beginPath(); context.rect(0, 0, this.bound.max.getX() - this.bound.min.getX(), this.bound.max.getY() - this.bound.min....
if (Vector2d.isGreater(max, box.bound.max)) { max = box.bound.max;
random_line_split
AABB.ts
import Vector2d from "../math/vector2d"; // Axis Aligned Bounding Box export default class BoundingBox { public static overlaps(boxA: BoundingBox, boxB: BoundingBox): boolean { return ( Vector2d.isLessOrEqual(boxA.bound.min, boxB.bound.max) && Vector2d.isLessOrEqual(boxB.bound.min, boxA.bound.max) ); } ...
} public draw(context) { context.save(); context.translate(this.bound.min.getX(), this.bound.min.getY()); context.beginPath(); context.rect(0, 0, this.bound.max.getX() - this.bound.min.getX(), this.bound.max.getY() - this.bound.min.getY()); context.lineWidth = 0.5; context.strokeStyle = "#00ff00"; con...
{ min = box.bound.min; }
conditional_block
AABB.ts
import Vector2d from "../math/vector2d"; // Axis Aligned Bounding Box export default class
{ public static overlaps(boxA: BoundingBox, boxB: BoundingBox): boolean { return ( Vector2d.isLessOrEqual(boxA.bound.min, boxB.bound.max) && Vector2d.isLessOrEqual(boxB.bound.min, boxA.bound.max) ); } public bound = { max: <Vector2d> null, min: <Vector2d> null, }; constructor(options?) { option...
BoundingBox
identifier_name
test_distributed_reader.py
# Copyright (c) 2019 PaddlePaddle 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 app...
(unittest.TestCase): def test_distributed_reader(self): trainer_num = 4 os.environ['PADDLE_TRAINER_ID'] = str(1) os.environ['PADDLE_TRAINERS_NUM'] = str(trainer_num) reader = fluid.contrib.reader.distributed_batch_reader(data_generator) data = next(reader()) assert d...
TestDistributedReader
identifier_name
test_distributed_reader.py
# Copyright (c) 2019 PaddlePaddle 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 app...
os.environ['PADDLE_TRAINERS_NUM'] = str(trainer_num) reader = fluid.contrib.reader.distributed_batch_reader(data_generator) data = next(reader()) assert data == 1 os.unsetenv('PADDLE_TRAINER_ID') os.unsetenv('PADDLE_TRAINERS_NUM') if __name__ == '__main__': unitte...
def test_distributed_reader(self): trainer_num = 4 os.environ['PADDLE_TRAINER_ID'] = str(1)
random_line_split
test_distributed_reader.py
# Copyright (c) 2019 PaddlePaddle 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 app...
if __name__ == '__main__': unittest.main()
def test_distributed_reader(self): trainer_num = 4 os.environ['PADDLE_TRAINER_ID'] = str(1) os.environ['PADDLE_TRAINERS_NUM'] = str(trainer_num) reader = fluid.contrib.reader.distributed_batch_reader(data_generator) data = next(reader()) assert data == 1 os.unse...
identifier_body
test_distributed_reader.py
# Copyright (c) 2019 PaddlePaddle 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 app...
unittest.main()
conditional_block
activation.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # 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...
(base.Resource): pass class ActivationManager(base.CrudManager): """Manager class for activating user in the USER REGISTRATION extension for Keystone. For more information about the extension: https://www.github.com/ging/keystone """ resource_class = Activation collection_key = 'activate' ...
Activation
identifier_name
activation.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # 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...
def activate_user(self, user, activation_key): base_url = self.base_url + '/users/{0}/'.format(base.getid(user)) return super(ActivationManager, self).update(base_url, activation_key)
base_url = self.base_url + '/users/{0}/'.format(base.getid(user)) return super(ActivationManager, self).get(base_url)
random_line_split
activation.py
# Copyright (C) 2014 Universidad Politecnica de Madrid # 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...
def activate_user(self, user, activation_key): base_url = self.base_url + '/users/{0}/'.format(base.getid(user)) return super(ActivationManager, self).update(base_url, activation_key)
base_url = self.base_url + '/users/{0}/'.format(base.getid(user)) return super(ActivationManager, self).get(base_url)
identifier_body
cookie-consent.js
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner // Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears var cookieName = 'EuCookieLa...
window.onload = function () { if (checkCookie(window.cookieName) != window.cookieValue) { createBanner(); } };
createCookie(name, '', -1); }
identifier_body
cookie-consent.js
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner // Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears var cookieName = 'EuCookieLa...
ame) { createCookie(name, '', -1); } window.onload = function () { if (checkCookie(window.cookieName) != window.cookieValue) { createBanner(); } };
aseCookie(n
identifier_name
cookie-consent.js
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner // Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears var cookieName = 'EuCookieLa...
} function checkCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); ...
var element = document.getElementById('cookie-law-banner'); element.parentNode.removeChild(element);
random_line_split
cookie-consent.js
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner // Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears var cookieName = 'EuCookieLa...
document.cookie = window.cookieName + '=' + window.cookieValue + expires + '; path=/'; var element = document.getElementById('cookie-law-banner'); element.parentNode.removeChild(element); } function checkCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); ...
expires = ''; }
conditional_block
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBindi...
format!("{:?}", self.code) } // https://heycam.github.io/webidl/#error-names fn Message(self) -> DOMString { let message = match self.code { DOMErrorName::IndexSizeError => "The index is not in the allowed range.", DOMErrorName::HierarchyRequestError => "The operatio...
random_line_split
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBindi...
(self) -> DOMString { format!("{:?}", self.code) } // https://heycam.github.io/webidl/#error-names fn Message(self) -> DOMString { let message = match self.code { DOMErrorName::IndexSizeError => "The index is not in the allowed range.", DOMErrorName::HierarchyRequest...
Name
identifier_name
domexception.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBindi...
// https://heycam.github.io/webidl/#error-names fn Message(self) -> DOMString { let message = match self.code { DOMErrorName::IndexSizeError => "The index is not in the allowed range.", DOMErrorName::HierarchyRequestError => "The operation would yield an incorrect node tree.", ...
{ format!("{:?}", self.code) }
identifier_body
gulpfile.js
'use strict'; /* all required gulp libs */ var gulp = require('gulp'); var gutil = require('gulp-util'); var clean = require('gulp-clean'); var flatmap = require('gulp-flatmap'); var fs = require('fs'); var path = require('path'); var argv = require('yargs').argv; var closureCompiler = require('google-closure-compiler...
() { DEBUG && console.log('getting extern files...'); return [].concat( getFilesInDirectory('src/externs/3rd-party'), getFilesInDirectory('src/externs/app/') ); } /** * get all files in a dir * * @param dir * @return {Array} */ function getFilesInDirectory(dir) { var allFileNames ...
getExternFiles
identifier_name
gulpfile.js
'use strict'; /* all required gulp libs */ var gulp = require('gulp'); var gutil = require('gulp-util'); var clean = require('gulp-clean'); var flatmap = require('gulp-flatmap'); var fs = require('fs'); var path = require('path'); var argv = require('yargs').argv; var closureCompiler = require('google-closure-compiler...
return gulp.src( [ DIST_RAW + '/app/MyApp.js' ], {base: './'}) .pipe(flatmap(function (stream, file) { return stream.pipe(closureCompiler({ compilation_level: 'ADVANCED', //manage_closure_dependencies: true, //warning_l...
], {base: DIST_RAW}) .pipe(gulp.dest(DIST_COMPILED)); } var externFiles = getExternFiles();
random_line_split
gulpfile.js
'use strict'; /* all required gulp libs */ var gulp = require('gulp'); var gutil = require('gulp-util'); var clean = require('gulp-clean'); var flatmap = require('gulp-flatmap'); var fs = require('fs'); var path = require('path'); var argv = require('yargs').argv; var closureCompiler = require('google-closure-compiler...
var externFiles = getExternFiles(); return gulp.src( [ DIST_RAW + '/app/MyApp.js' ], {base: './'}) .pipe(flatmap(function (stream, file) { return stream.pipe(closureCompiler({ compilation_level: 'ADVANCED', //manage_closure_depen...
{ return gulp.src( [ DIST_RAW + '/app/MyApp.js' ], {base: DIST_RAW}) .pipe(gulp.dest(DIST_COMPILED)); }
conditional_block
gulpfile.js
'use strict'; /* all required gulp libs */ var gulp = require('gulp'); var gutil = require('gulp-util'); var clean = require('gulp-clean'); var flatmap = require('gulp-flatmap'); var fs = require('fs'); var path = require('path'); var argv = require('yargs').argv; var closureCompiler = require('google-closure-compiler...
{ var allFileNames = fs.readdirSync(dir); var allFiles = []; allFileNames.map(function (file) { return path.join(dir, file); }).filter(function (file) { return fs.statSync(file).isFile(); }).forEach(function (file) { DEBUG && console.log(" %s", file); allFiles.pus...
identifier_body
evaluateCloudFormationChangeSetExecutionLabel.tsx
import * as React from 'react'; import { OverlayTrigger, Tooltip } from 'react-bootstrap'; import type { IExecution, IExecutionStageSummary } from '@spinnaker/core'; import type { Application } from '@spinnaker/core'; import { ExecutionBarLabel, HoverablePopover } from '@spinnaker/core'; import { EvaluateCloudFormati...
</OverlayTrigger> ); } }
{ const template = ( <div> <div> <b>{stage.name}</b> </div> <EvaluateCloudFormationChangeSetExecutionApproval stage={stage.masterStage} application={this.props.application} execution={this.props.execution} /> ...
conditional_block
evaluateCloudFormationChangeSetExecutionLabel.tsx
import * as React from 'react'; import { OverlayTrigger, Tooltip } from 'react-bootstrap'; import type { IExecution, IExecutionStageSummary } from '@spinnaker/core'; import type { Application } from '@spinnaker/core'; import { ExecutionBarLabel, HoverablePopover } from '@spinnaker/core'; import { EvaluateCloudFormati...
() { if (!this.props.executionMarker) { return <ExecutionBarLabel {...this.props} />; } const { stage } = this.props; if ( stage.isRunning && stage.stages[0].context.changeSetContainsReplacement && stage.stages[0].context.actionOnReplacement === 'ask' ) { const templat...
render
identifier_name
evaluateCloudFormationChangeSetExecutionLabel.tsx
import * as React from 'react'; import { OverlayTrigger, Tooltip } from 'react-bootstrap'; import type { IExecution, IExecutionStageSummary } from '@spinnaker/core'; import type { Application } from '@spinnaker/core'; import { ExecutionBarLabel, HoverablePopover } from '@spinnaker/core'; import { EvaluateCloudFormati...
execution={this.props.execution} /> </div> ); return <HoverablePopover template={template}>{this.props.children}</HoverablePopover>; } const tooltip = <Tooltip id={stage.id}>{stage.name}</Tooltip>; return ( <OverlayTrigger placement="top" overlay={tooltip}> ...
{ if (!this.props.executionMarker) { return <ExecutionBarLabel {...this.props} />; } const { stage } = this.props; if ( stage.isRunning && stage.stages[0].context.changeSetContainsReplacement && stage.stages[0].context.actionOnReplacement === 'ask' ) { const template =...
identifier_body
evaluateCloudFormationChangeSetExecutionLabel.tsx
import * as React from 'react'; import { OverlayTrigger, Tooltip } from 'react-bootstrap'; import type { IExecution, IExecutionStageSummary } from '@spinnaker/core'; import type { Application } from '@spinnaker/core'; import { ExecutionBarLabel, HoverablePopover } from '@spinnaker/core'; import { EvaluateCloudFormati...
<EvaluateCloudFormationChangeSetExecutionApproval stage={stage.masterStage} application={this.props.application} execution={this.props.execution} /> </div> ); return <HoverablePopover template={template}>{this.props.children}</HoverablePopover...
</div>
random_line_split
unix.rs
#![cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", ))] use crate::platform::ContextTraitExt; pub use crate::platform_impl::{HeadlessContextExt, RawContextExt, RawHandle}; use crate::{Context, ContextCurrentState}; pub use gl...
#[inline] unsafe fn get_egl_display(&self) -> Option<*const raw::c_void> { self.context.get_egl_display() } }
{ self.context.raw_handle() }
identifier_body
unix.rs
#![cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", ))] use crate::platform::ContextTraitExt; pub use crate::platform_impl::{HeadlessContextExt, RawContextExt, RawHandle}; use crate::{Context, ContextCurrentState}; pub use gl...
(&self) -> Option<*const raw::c_void> { self.context.get_egl_display() } }
get_egl_display
identifier_name
unix.rs
#![cfg(any( target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", ))] use crate::platform::ContextTraitExt; pub use crate::platform_impl::{HeadlessContextExt, RawContextExt, RawHandle}; use crate::{Context, ContextCurrentState}; pub use gl...
self.context.get_egl_display() } }
#[inline] unsafe fn get_egl_display(&self) -> Option<*const raw::c_void> {
random_line_split
presetParsing-1.py
########################################################################## # # Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE ...
# written permission. #
random_line_split
presetParsing-1.py
########################################################################## # # Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
IECore.registerRunTimeTyped( presetParsing )
assert operands["h"] == IECore.V3fData( imath.V3f( 1, 0, 0 ) ) assert operands["i"] == IECore.V2dData( imath.V2d( 0 ) ) compoundPreset = IECore.CompoundObject() compoundPreset["j"] = IECore.V3dData( imath.V3d( 1 ) ) compoundPreset["k"] = IECore.M44fData( imath.M44f( 1 ) ) assert operands["compound"] == comp...
identifier_body
presetParsing-1.py
########################################################################## # # Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
( self, operands ) : assert operands["h"] == IECore.V3fData( imath.V3f( 1, 0, 0 ) ) assert operands["i"] == IECore.V2dData( imath.V2d( 0 ) ) compoundPreset = IECore.CompoundObject() compoundPreset["j"] = IECore.V3dData( imath.V3d( 1 ) ) compoundPreset["k"] = IECore.M44fData( imath.M44f( 1 ) ) assert oper...
doOperation
identifier_name
userService.js
/* * The MIT License * Copyright (c) 2014-2016 Nick Guletskii * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, c...
} approveUsers(users) { return this.$http.post("/api/admin/users/approve", users) .then(_property("data")); } deleteUsers(users) { return this.$http.post("/api/admin/users/deleteUsers", users) .then(_property("data")); } countArchiveUsers() { return this.$http.get("/api/archive/rankCount") .then(_...
params: { id } }) .then(_property("data"));
random_line_split
userService.js
/* * The MIT License * Copyright (c) 2014-2016 Nick Guletskii * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, c...
getUserById(id) { return this.$http.get("/api/user", { params: { id } }) .then(_property("data")); } approveUsers(users) { return this.$http.post("/api/admin/users/approve", users) .then(_property("data")); } deleteUsers(users) { return this.$http.post("/api/admin/users/deleteUsers", use...
{ return this.$http.get("/api/admin/users", { params: { page } }) .then(_property("data")); }
identifier_body
userService.js
/* * The MIT License * Copyright (c) 2014-2016 Nick Guletskii * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, c...
() { return this.$http.get("/api/archive/rankCount") .then(_property("data")); } getArchiveRankPage(page) { return this.$http.get("/api/archive/rank", { params: { page } }) .then(_property("data")); } addUserToGroup(groupId, username) { const deferred = this.$q.defer(); const formData = n...
countArchiveUsers
identifier_name
20170323200721_expense_items.js
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().refer...
table.index('expense_id') }) }) .then(() => { // this is necessary BEFORE creating the expense items because knex // drops the expenses table and then recreates it (foreign key problem). console.log('Dropping "preTaxAmount" and "taxrate" columns in expenses') return knex.s...
random_line_split
20170323200721_expense_items.js
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().refer...
{ return knex('expense_items') .insert({ expense_id: expense.id, position: 0, preTaxAmount: expense.preTaxAmount, taxrate: expense.taxrate, description: '' }) }
identifier_body
20170323200721_expense_items.js
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().refer...
(knex, expense) { return knex('expense_items') .insert({ expense_id: expense.id, position: 0, preTaxAmount: expense.preTaxAmount, taxrate: expense.taxrate, description: '' }) }
createExpenseItem
identifier_name
controller.js
const request = require('request') const {NotFoundError, TranslationError} = require('../core/errors') const RoutesService = require('../routes/service') function getUri(robot) { if (robot === 'julinha') { return 'http://' + process.env.JULINHA_TRANSLATOR_HOST + ':3000/json' } return 'http://' + process.env...
(req, res, next) { try { const routesService = new RoutesService(res.locals.databaseConnection) const {route: name, robot} = req.body const route = await routesService.findByName(name) if (!route || Object.keys(route).length === 0) { throw new NotFoundError() } const options = { ...
walk
identifier_name
controller.js
const request = require('request') const {NotFoundError, TranslationError} = require('../core/errors') const RoutesService = require('../routes/service') function getUri(robot) { if (robot === 'julinha') { return 'http://' + process.env.JULINHA_TRANSLATOR_HOST + ':3000/json' } return 'http://' + process.env...
res.json({ message: 'Route sent with success!' }) }) } catch (err) { if (err.name === NotFoundError.name) { return res.status(404).json({ message: 'Route not found' }) } if (err.name === TranslationError.name) { return res.status(500).json({ messa...
{ try { const routesService = new RoutesService(res.locals.databaseConnection) const {route: name, robot} = req.body const route = await routesService.findByName(name) if (!route || Object.keys(route).length === 0) { throw new NotFoundError() } const options = { method: 'POST', ...
identifier_body
controller.js
const request = require('request') const {NotFoundError, TranslationError} = require('../core/errors') const RoutesService = require('../routes/service') function getUri(robot) { if (robot === 'julinha') { return 'http://' + process.env.JULINHA_TRANSLATOR_HOST + ':3000/json' } return 'http://' + process.env...
if (!route || Object.keys(route).length === 0) { throw new NotFoundError() } const options = { method: 'POST', uri: getUri(robot), body: JSON.stringify(route) } request(options, err => { if (err) { throw new TranslationError() } res.json({ ...
const {route: name, robot} = req.body const route = await routesService.findByName(name)
random_line_split
controller.js
const request = require('request') const {NotFoundError, TranslationError} = require('../core/errors') const RoutesService = require('../routes/service') function getUri(robot) { if (robot === 'julinha') { return 'http://' + process.env.JULINHA_TRANSLATOR_HOST + ':3000/json' } return 'http://' + process.env...
res.json({ message: 'Route sent with success!' }) }) } catch (err) { if (err.name === NotFoundError.name) { return res.status(404).json({ message: 'Route not found' }) } if (err.name === TranslationError.name) { return res.status(500).json({ mess...
{ throw new TranslationError() }
conditional_block
macro-interpolation.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!(overly_complicated!(f, x, Option<uint>, { return Some(x); }, Some(8u), Some(y), y) == 8u) }
identifier_body
macro-interpolation.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 $fnname($arg: $ty) -> Option<$ty> $body match $fnname($val) { Some($pat) => { $res } _ => { fail2!(); } } }) ) pub fn main() { assert!(overly_complicated!(f, x, Option<uint>, { return Some(x); }, Some(8u), Some(...
random_line_split
macro-interpolation.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!(overly_complicated!(f, x, Option<uint>, { return Some(x); }, Some(8u), Some(y), y) == 8u) }
main
identifier_name
test_diagnostics.py
# Licensed under the MIT License - https://opensource.org/licenses/MIT import unittest import pytest import numpy as np from pycobra.cobra import Cobra from pycobra.ewa import Ewa from pycobra.diagnostics import Diagnostics import logging class
(unittest.TestCase): def setUp(self): # setting up our random data-set rng = np.random.RandomState(42) # D1 = train machines; D2 = create COBRA; D3 = calibrate epsilon, alpha; D4 = testing n_features = 20 D1, D2, D3, D4 = 200, 200, 200, 200 D = D1 + D2 + D3 + D4 ...
TestOptimal
identifier_name
test_diagnostics.py
# Licensed under the MIT License - https://opensource.org/licenses/MIT import unittest import pytest import numpy as np from pycobra.cobra import Cobra from pycobra.ewa import Ewa from pycobra.diagnostics import Diagnostics import logging class TestOptimal(unittest.TestCase): def setUp(self): # setting ...
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) unittest.main()
conditional_block
test_diagnostics.py
# Licensed under the MIT License - https://opensource.org/licenses/MIT import unittest import pytest import numpy as np from pycobra.cobra import Cobra from pycobra.ewa import Ewa from pycobra.diagnostics import Diagnostics import logging class TestOptimal(unittest.TestCase): def setUp(self): # setting ...
if __name__ == '__main__': logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) unittest.main()
random_line_split
test_diagnostics.py
# Licensed under the MIT License - https://opensource.org/licenses/MIT import unittest import pytest import numpy as np from pycobra.cobra import Cobra from pycobra.ewa import Ewa from pycobra.diagnostics import Diagnostics import logging class TestOptimal(unittest.TestCase): def setUp(self): # setting ...
@pytest.mark.slow def test_alpha_grid(self): (alpha, epsilon), mse = self.cobra_diagnostics.optimal_alpha_grid(self.test_data[0], self.test_response[0]) expected_alpha, expected_mse = 1, 0.01331659692231877 self.assertEqual(expected_alpha, alpha) self.assertAlmostEqual(expected...
alpha, mse = self.cobra_diagnostics.optimal_alpha(self.test_data, self.test_response) expected_alpha, expected_mse = 5, 0.06878994911340372 self.assertEqual(expected_alpha, alpha) self.assertAlmostEqual(expected_mse, mse, places=3)
identifier_body
router_testing_module.d.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 { Location } from '@angular/common'; import { Compiler, Injector, ModuleWithProviders, NgModuleFactory, NgModu...
stubbedModules: { [path: string]: any; }; constructor(compiler: Compiler); load(path: string): Promise<NgModuleFactory<any>>; } /** * Router setup factory function used for testing. * * @stable */ export declare function setupTestingRouter(urlSerializer: UrlSerializer, outletMap: RouterOutle...
* @docsNotRequired */ /** * @docsNotRequired */
random_line_split
router_testing_module.d.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 { Location } from '@angular/common'; import { Compiler, Injector, ModuleWithProviders, NgModuleFactory, NgModu...
implements NgModuleFactoryLoader { private compiler; /** * @docsNotRequired */ private _stubbedModules; /** * @docsNotRequired */ /** * @docsNotRequired */ stubbedModules: { [path: string]: any; }; constructor(compiler: Compiler); load(path: str...
SpyNgModuleFactoryLoader
identifier_name
LivechatPageVisited.js
/** * Livechat Page Visited model */ class LivechatPageVisited extends CaoLiao.models._Base { constructor() { super(); this._initModel('livechat_page_visited'); this.tryEnsureIndex({ 'token': 1 }); this.tryEnsureIndex({ 'ts': 1 }); // keep history for 1 month if the visitor does not register this.tryEn...
(token) { return this.update({ token: token, expireAt: { $exists: true } }, { $unset: { expireAt: 1 } }, { multi: true }); } } CaoLiao.models.LivechatPageVisited = new LivechatPageVisited();
keepHistoryForToken
identifier_name
LivechatPageVisited.js
/** * Livechat Page Visited model */ class LivechatPageVisited extends CaoLiao.models._Base { constructor() { super(); this._initModel('livechat_page_visited'); this.tryEnsureIndex({ 'token': 1 }); this.tryEnsureIndex({ 'ts': 1 }); // keep history for 1 month if the visitor does not register this.tryEn...
keepHistoryForToken(token) { return this.update({ token: token, expireAt: { $exists: true } }, { $unset: { expireAt: 1 } }, { multi: true }); } } CaoLiao.models.LivechatPageVisited = new LivechatPageVisited();
findByToken(token) { return this.find({ token: token }, { sort : { ts: -1 }, limit: 20 }); }
random_line_split
LivechatPageVisited.js
/** * Livechat Page Visited model */ class LivechatPageVisited extends CaoLiao.models._Base { constructor() { super(); this._initModel('livechat_page_visited'); this.tryEnsureIndex({ 'token': 1 }); this.tryEnsureIndex({ 'ts': 1 }); // keep history for 1 month if the visitor does not register this.tryEn...
findByToken(token) { return this.find({ token: token }, { sort : { ts: -1 }, limit: 20 }); } keepHistoryForToken(token) { return this.update({ token: token, expireAt: { $exists: true } }, { $unset: { expireAt: 1 } }, { multi: true }); } } CaoLiao.models.LivechatPageVisited = ...
{ // keep history of unregistered visitors for 1 month var keepHistoryMiliseconds = 2592000000; return this.insert({ token: token, page: pageInfo, ts: new Date(), expireAt: new Date().getTime() + keepHistoryMiliseconds }); }
identifier_body
transform_hex_multine.py
#! /usr/bin/python3 import sys MAXLINELEN = 80 TABLEN = 8 # 3 for two quotes and a comma FIRSTLINELEN = MAXLINELEN - TABLEN - 3 OTHERLINELEN = FIRSTLINELEN - 2 * TABLEN FIRSTLINEBYTES = FIRSTLINELEN // 2 OTHERLINEBYTES = OTHERLINELEN // 2 def fix_line(line): return "".join("\\x{}".format(line[i:i + 2].decode()) f...
f.write("};\n") if __name__ == "__main__": main();
f.write("\t\"{}\"".format(fix_line(line[:FIRSTLINEBYTES]))) if len(line) > FIRSTLINEBYTES: line = line[FIRSTLINEBYTES:] while line: f.write("\n\t\t\t\"{}\"".format( fix_line(line[:OTHERLINEBYTES]))) line = line[OTHERLINEBYTES:] f.write(",\n")
conditional_block
transform_hex_multine.py
#! /usr/bin/python3 import sys MAXLINELEN = 80 TABLEN = 8 # 3 for two quotes and a comma FIRSTLINELEN = MAXLINELEN - TABLEN - 3 OTHERLINELEN = FIRSTLINELEN - 2 * TABLEN FIRSTLINEBYTES = FIRSTLINELEN // 2 OTHERLINEBYTES = OTHERLINELEN // 2 def fix_line(line):
with sys.stdout as f: f.write("#define INPUTLEN {}\n".format(len(data[0]) // 2)) f.write("\n") f.write("static const unsigned char input[][INPUTLEN + 1] = {\n") for line in data: f.write("\t\"{}\"".format(fix_line(line[:FIRSTLINEBYTES]))) if len(line) > FIRSTLINEBYTES: line = line[FIRSTLINEBYTES:] ...
return "".join("\\x{}".format(line[i:i + 2].decode()) for i in range(0, len(line), 2)) def main(): with open(sys.argv[1], "rb") as f: data = f.read().strip().splitlines()
random_line_split