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
app.js
'use strict'; (function(module) { function MyProject (proj) { for (let keys in proj) { this[keys] = proj[keys] } } MyProject.allProjects = []; MyProject.prototype.toHtml = function() { var htmlTemplate = $('#template').html(); var template = Handlebars.compile(htmlTemplate); return...
}; MyProject.displayTheGroupProjects = function() { return MyProject.allProjects.map(function(projects2) { return projects2 }) .reduce(function(acc, curr) { if (acc.indexOf(curr) === -1) { acc.push(curr) } return acc; }, []); } //MyProject.displayTheGroupProject...
{ $.getJSON('./data/projects.json').then( function(data) { localStorage.setItem('projects', JSON.stringify(data)) var lData = JSON.parse(localStorage.getItem('projects')); MyProject.loadAll(lData); MyProject.showProjects(lData) } ); }
conditional_block
app.js
'use strict'; (function(module) { function MyProject (proj)
MyProject.allProjects = []; MyProject.prototype.toHtml = function() { var htmlTemplate = $('#template').html(); var template = Handlebars.compile(htmlTemplate); return template(this); }; MyProject.loadAll = function(project) { project.forEach(function(ele) { MyProject.allProjects.push(...
{ for (let keys in proj) { this[keys] = proj[keys] } }
identifier_body
app.js
'use strict'; (function(module) { function
(proj) { for (let keys in proj) { this[keys] = proj[keys] } } MyProject.allProjects = []; MyProject.prototype.toHtml = function() { var htmlTemplate = $('#template').html(); var template = Handlebars.compile(htmlTemplate); return template(this); }; MyProject.loadAll = function(pr...
MyProject
identifier_name
app.js
'use strict'; (function(module) { function MyProject (proj) { for (let keys in proj) { this[keys] = proj[keys] } } MyProject.allProjects = []; MyProject.prototype.toHtml = function() { var htmlTemplate = $('#template').html(); var template = Handlebars.compile(htmlTemplate); return...
.reduce(function(acc, curr) { if (acc.indexOf(curr) === -1) { acc.push(curr) } return acc; }, []); } //MyProject.displayTheGroupProjects(); module.MyProject = MyProject; })(window);
})
random_line_split
main.rs
extern crate piston; // piston core extern crate graphics; // piston graphics extern crate glutin_window; // opengl context creation extern crate opengl_graphics; // opengl binding //extern crate find_folder; // for finding our assets folder. extern crate time; extern crate rand; extern crate ncollide; // 2d/3d/nd co...
let opengl = OpenGL::V3_2; let (width, height) = (1280, 720); // Create an Glutin window. let mut window: Window = WindowSettings::new("Snake Game", [width, height]) .opengl(opengl) .exit_on_esc(true) .vsync(true) .fullscreen(false) .build() .unwrap(); ...
random_line_split
main.rs
extern crate piston; // piston core extern crate graphics; // piston graphics extern crate glutin_window; // opengl context creation extern crate opengl_graphics; // opengl binding //extern crate find_folder; // for finding our assets folder. extern crate time; extern crate rand; extern crate ncollide; // 2d/3d/nd co...
if let Some(u) = e.update_args() { // Simulate lag: // std::thread::sleep(std::time::Duration::new(0, 1000_000_00)); app.update(&u); } } }
{ app.render(&r); }
conditional_block
main.rs
extern crate piston; // piston core extern crate graphics; // piston graphics extern crate glutin_window; // opengl context creation extern crate opengl_graphics; // opengl binding //extern crate find_folder; // for finding our assets folder. extern crate time; extern crate rand; extern crate ncollide; // 2d/3d/nd co...
(&mut self, args: &RenderArgs) { if self.should_render { self.window_rect = Vector2::new(args.width, args.height); use graphics::*; const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; let world_state = &self.world_state; let viewport = args.viewport(); ...
render
identifier_name
main.rs
extern crate piston; // piston core extern crate graphics; // piston graphics extern crate glutin_window; // opengl context creation extern crate opengl_graphics; // opengl binding //extern crate find_folder; // for finding our assets folder. extern crate time; extern crate rand; extern crate ncollide; // 2d/3d/nd co...
} fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V3_2; let (width, height) = (1280, 720); // Create an Glutin window. let mut window: Window = WindowSettings::new("Snake Game", [width, height]) .opengl(opengl) .exit_on_esc(true) .vsync(tr...
{ self.world_state.window_rect = self.window_rect; self.world_state.update(args); }
identifier_body
tests.py
# -*- encoding: utf-8 -*- """ Tests for django.core.servers. """ from __future__ import unicode_literals import os import socket from django.core.exceptions import ImproperlyConfigured from django.test import LiveServerTestCase from django.test.utils import override_settings from django.utils.http import urlencode fr...
def test_database_writes(self): """ Ensure that data written to the database by a view can be read. Refs #2879. """ self.urlopen('/create_model_instance/') self.assertQuerysetEqual( Person.objects.all().order_by('pk'), ['jane', 'robert', 'emily']...
Ensure that fixtures are properly loaded and visible to the live server thread. Refs #2879. """ f = self.urlopen('/model_view/') self.assertEqual(f.read().splitlines(), [b'jane', b'robert'])
identifier_body
tests.py
# -*- encoding: utf-8 -*- """ Tests for django.core.servers. """ from __future__ import unicode_literals import os import socket from django.core.exceptions import ImproperlyConfigured from django.test import LiveServerTestCase from django.test.utils import override_settings from django.utils.http import urlencode fr...
available_apps = [ 'servers', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ] fixtures = ['testdata.json'] urls = 'servers.urls' @classmethod def setUpClass(cls): # Override settings cls.settings_override = overr...
random_line_split
tests.py
# -*- encoding: utf-8 -*- """ Tests for django.core.servers. """ from __future__ import unicode_literals import os import socket from django.core.exceptions import ImproperlyConfigured from django.test import LiveServerTestCase from django.test.utils import override_settings from django.utils.http import urlencode fr...
(cls): # skip it, as setUpClass doesn't call its parent either pass @classmethod def raises_exception(cls, address, exception): os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = address try: super(LiveServerAddress, cls).setUpClass() raise Exception("The li...
tearDownClass
identifier_name
tests.py
# -*- encoding: utf-8 -*- """ Tests for django.core.servers. """ from __future__ import unicode_literals import os import socket from django.core.exceptions import ImproperlyConfigured from django.test import LiveServerTestCase from django.test.utils import override_settings from django.utils.http import urlencode fr...
else: del os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] @classmethod def tearDownClass(cls): # skip it, as setUpClass doesn't call its parent either pass @classmethod def raises_exception(cls, address, exception): os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS...
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = old_address
conditional_block
unit-return.rs
// aux-build:unit-return.rs #![crate_name = "foo"] extern crate unit_return; // @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone' pub fn f0<F: FnMut(u8) + Clone>(f: F) {}
// @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone' pub fn f1<F: FnMut(u16) -> () + Clone>(f: F) {} // @has 'foo/fn.f2.html' '//*[@class="rust fn"]' 'F: FnMut(u32) + Clone' pub use unit_return::f2; // @has 'foo/fn.f3.html' '//*[@class="rust fn"]' 'F: FnMut(u64) + Clone' pub use unit_return::f3;
random_line_split
unit-return.rs
// aux-build:unit-return.rs #![crate_name = "foo"] extern crate unit_return; // @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone' pub fn f0<F: FnMut(u8) + Clone>(f: F)
// @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone' pub fn f1<F: FnMut(u16) -> () + Clone>(f: F) {} // @has 'foo/fn.f2.html' '//*[@class="rust fn"]' 'F: FnMut(u32) + Clone' pub use unit_return::f2; // @has 'foo/fn.f3.html' '//*[@class="rust fn"]' 'F: FnMut(u64) + Clone' pub use unit_return::f3;...
{}
identifier_body
unit-return.rs
// aux-build:unit-return.rs #![crate_name = "foo"] extern crate unit_return; // @has 'foo/fn.f0.html' '//*[@class="rust fn"]' 'F: FnMut(u8) + Clone' pub fn f0<F: FnMut(u8) + Clone>(f: F) {} // @has 'foo/fn.f1.html' '//*[@class="rust fn"]' 'F: FnMut(u16) + Clone' pub fn
<F: FnMut(u16) -> () + Clone>(f: F) {} // @has 'foo/fn.f2.html' '//*[@class="rust fn"]' 'F: FnMut(u32) + Clone' pub use unit_return::f2; // @has 'foo/fn.f3.html' '//*[@class="rust fn"]' 'F: FnMut(u64) + Clone' pub use unit_return::f3;
f1
identifier_name
in.js
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this li...
assertTrue('toString' in o, "toString"); var o = {}; o[Math.pow(2,30)-1] = 0; o[Math.pow(2,31)-1] = 0; o[1] = 0; assertFalse(0 in o); assertTrue(1 in o); assertFalse(2 in o); assertFalse(Math.pow(2,30)-2 in o); assertTrue(Math.pow(2,30)-1 in o); assertFalse(Math.pow(2,30)-0 in o); assertTrue(Math.pow(2,3...
{ assertTrue('char:' + String.fromCharCode(i) in o); assertFalse('char:' + String.fromCharCode(i + 1) in o); }
conditional_block
in.js
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this li...
assertTrue('toString' in o, "toString"); // ---------------- // Check sparse arrays var a = []; a[Math.pow(2,30)-1] = 0; a[Math.pow(2,31)-1] = 0; a[1] = 0; assertFalse(0 in a, "0 in a"); assertTrue(1 in a, "1 in a"); assertFalse(2 in a, "2 in a"); assertFalse(Math.pow(2,30)-2 in a, "Math.pow(2,30)-2 in ...
random_line_split
setup.py
# -*- coding: utf-8 -*- # BankCSVtoQif - Smart conversion of csv files from a bank to qif # Copyright (C) 2015-2016 Nikolai Nowaczyk # # This program 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 v...
license='GNU GPLv2', url='https://github.com/niknow/BankCSVtoQif/tree/master/bankcsvtoqif', packages=find_packages(), test_suite='bankcsvtoqif.tests', tests_require=['pytest'], install_requires=['monthdelta'] )
author_email='mail@nikno.de',
random_line_split
ProgressIndicator.d.ts
import * as React from "react"; import { ReactAttr, ReactInputAttr, ValidityProps, InternationalProps } from "../../../typings/shared"; // ProgressStep export type ProgressStepTranslationKey = "carbon.progress-step.complete" | "carbon.progress-step.incomplete" | "carbon.progress-step.current" | "carbo...
export declare class ProgressIndicator extends React.Component<ProgressIndicatorProps> { }
random_line_split
ProgressIndicator.d.ts
import * as React from "react"; import { ReactAttr, ReactInputAttr, ValidityProps, InternationalProps } from "../../../typings/shared"; // ProgressStep export type ProgressStepTranslationKey = "carbon.progress-step.complete" | "carbon.progress-step.incomplete" | "carbon.progress-step.current" | "carbo...
extends React.Component<ProgressIndicatorProps> { }
ProgressIndicator
identifier_name
main.js
Date.prototype.format = function(format) { var o = {
"h+" : this.getHours(), // hour "m+" : this.getMinutes(), // minute "s+" : this.getSeconds(), // second "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter "S" : this.getMilliseconds() // millisecond }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "") .substr...
"M+" : this.getMonth() + 1, // month "d+" : this.getDate(), // day
random_line_split
base.py
import logging import json from ansible.runner import Runner from taskflow.patterns import linear_flow, unordered_flow from taskflow.task import Task shell_task = Runner( host_list=['eselnlx1453'], pattern= '*', module_name = 'shell', module_args='echo "Hello World"') c...
def create(self, name, tasks): ul_flow = self.create_flow(name) for task in tasks: ul_flow.add(task) return ul_flow class UnorderedFlowCreator(FlowCreator): def create_flow(self, name): return unordered_flow.Flow(name) class LinearFlowCreator(FlowCreator): def...
raise NotImplementedError()
identifier_body
base.py
import logging import json from ansible.runner import Runner from taskflow.patterns import linear_flow, unordered_flow from taskflow.task import Task shell_task = Runner( host_list=['eselnlx1453'], pattern= '*', module_name = 'shell', module_args='echo "Hello World"') c...
class LinearFlowCreator(FlowCreator): def create_flow(self, name): return linear_flow.Flow(name)
def create_flow(self, name): return unordered_flow.Flow(name)
random_line_split
base.py
import logging import json from ansible.runner import Runner from taskflow.patterns import linear_flow, unordered_flow from taskflow.task import Task shell_task = Runner( host_list=['eselnlx1453'], pattern= '*', module_name = 'shell', module_args='echo "Hello World"') c...
(AnsibleTask): def __init__(self, name, host_list, module_args, pattern='*', inject=None): super(ShellTask, self).__init__(name, host_list, 'shell', module_args, pattern, inject) class FlowCreator(object): def create_flow(self, name): raise NotImplementedError() def create(self, name, task...
ShellTask
identifier_name
base.py
import logging import json from ansible.runner import Runner from taskflow.patterns import linear_flow, unordered_flow from taskflow.task import Task shell_task = Runner( host_list=['eselnlx1453'], pattern= '*', module_name = 'shell', module_args='echo "Hello World"') c...
return ul_flow class UnorderedFlowCreator(FlowCreator): def create_flow(self, name): return unordered_flow.Flow(name) class LinearFlowCreator(FlowCreator): def create_flow(self, name): return linear_flow.Flow(name)
ul_flow.add(task)
conditional_block
astconv.rs
::DefPrimTy(ast::TyStr)) if a_seq_ty.mutbl == ast::MutImmutable => { check_path_args(tcx, path, NO_TPS | NO_REGIONS); return ty::mk_str(tcx, vst); } Some(&ast::DefTrait(trait_def_id)) => { let result = ast_pa...
} _ => { tcx.sess.span_fatal(ast_ty.span, format!("found value name used as a type: {:?}", a_def));
random_line_split
astconv.rs
match anon_regions { Ok(v) => opt_vec::from(v), Err(()) => opt_vec::from(vec::from_fn(expected_num_region_params, |_| ty::ReStatic)) // hokey } }; // Convert the type parameters supplied by the user. let supplied_type...
{ tcx.sess.span_err(ast_ty.span, "bare `[]` is not a type"); // return /something/ so they can at least get more errors ty::mk_vec(tcx, ast_ty_to_mt(this, rscope, ty), ty::vstore_uniq) }
conditional_block
astconv.rs
== supplied_num_region_params { path.segments.last().lifetimes.map( |l| ast_region_to_region(this.tcx(), l)) } else { let anon_regions = rscope.anon_regions(path.span, expected_num_region_params); if supplied_num_region_params != 0 || anon_regions.is_err() { ...
<AC:AstConv, RS:RegionScope>( this: &AC, rscope: &RS, mt: &ast::MutTy) -> ty::mt { ty::mt {ty: ast_ty_to_ty(this, rscope, mt.ty), mutbl: mt.mutbl} } // Handle @, ~, and & being able to mean strs and vecs. // If a_seq_ty is a str or a vec, make it an str/vec. // Also handle first-class ...
ast_mt_to_mt
identifier_name
astconv.rs
== supplied_num_region_params { path.segments.last().lifetimes.map( |l| ast_region_to_region(this.tcx(), l)) } else { let anon_regions = rscope.anon_regions(path.span, expected_num_region_params); if supplied_num_region_params != 0 || anon_regions.is_err() { ...
pub fn ast_path_to_ty<AC:AstConv,RS:RegionScope>( this: &AC, rscope: &RS, did: ast::DefId, path: &ast::Path) -> ty_param_substs_and_ty { // Look up the polytype of the item and then substitute the provided types // for any type/region parameters. let ty::ty_param_subst...
{ let trait_def = this.get_trait_def(trait_def_id); let substs = ast_path_substs( this, rscope, &trait_def.generics, self_ty, path); let trait_ref = @ty::TraitRef {def_id: trait_def_id, substs: substs}...
identifier_body
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations. use flow::{self, Flow}; use incremental::{self, RestyleDamage}; use clock_ti...
fragment.style = new_style }); let base = flow::mut_base(flow); base.restyle_damage.insert(damage); for kid in base.children.iter_mut() { recalc_style_for_animation(kid, animation) } } /// Handles animation updates. pub fn tick_all_animations(layout_task: &LayoutTask, rw_data: &mu...
{ #![allow(unsafe_code)] // #6376 let mut damage = RestyleDamage::empty(); flow.mutate_fragments(&mut |fragment| { if fragment.node.id() != animation.node { return } let now = clock_ticks::precise_time_s() as f32; let mut progress = (now - animation.start_time) /...
identifier_body
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations. use flow::{self, Flow}; use incremental::{self, RestyleDamage}; use clock_ti...
} else { animation_state = AnimationState::AnimationsPresent; } rw_data.constellation_chan .0 .send(Msg::ChangeRunningAnimationsState(pipeline_id, animation_state)) .unwrap(); } /// Recalculates style for an animation. This does *not* run with the DOM lock held. p...
} let animation_state; if rw_data.running_animations.is_empty() { animation_state = AnimationState::NoAnimationsPresent;
random_line_split
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations. use flow::{self, Flow}; use incremental::{self, RestyleDamage}; use clock_ti...
(new_animations_sender: &Sender<Animation>, node: OpaqueNode, old_style: &ComputedValues, new_style: &mut ComputedValues) { for i in 0..new_style.get_animation().transition_property.0.len() { ...
start_transitions_if_applicable
identifier_name
animation.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! CSS transitions and animations. use flow::{self, Flow}; use incremental::{self, RestyleDamage}; use clock_ti...
if progress <= 0.0 { return } let mut new_style = fragment.style.clone(); animation.property_animation.update(&mut *unsafe { new_style.make_unique() }, progress); damage.insert(incremental::compute_damage(&Some(fragment.style.clone()), &new_style)); fragment...
{ progress = 1.0 }
conditional_block
index.web.tsx
/* tslint:disable:jsx-no-multiline-js */ import React from 'react'; import classNames from 'classnames'; import Flex from '../flex'; import Carousel from '../carousel/index.web'; import { DataItem, GridProps } from './PropsType'; export default class Grid extends React.Component<GridProps, any> { static defaultProps...
else { // 空节点为了确保末尾页的最后未到底的行有底线(样式中last-child会没线) pageRows.push(<div key={`gridline-${rowIndex}`} />); } } pagesArr.push(<div key={`pageitem-${pageIndex}`} className={`${prefixCls}-carousel-page`}>{pageRows}</div>); } } return ( <div classN...
{ pageRows.push(rowsArr[rowIndex]); }
conditional_block
index.web.tsx
/* tslint:disable:jsx-no-multiline-js */ import React from 'react'; import classNames from 'classnames'; import Flex from '../flex'; import Carousel from '../carousel/index.web'; import { DataItem, GridProps } from './PropsType'; export default class Grid extends React.Component<GridProps, any> { static defaultProps...
const rowArr: any[] = []; for (let j = 0; j < columnNum; j++) { const dataIndex = i * columnNum + j; if (dataIndex < dataLength) { const el = data && data[dataIndex]; rowArr.push(<Flex.Item key={`griditem-${dataIndex}`} className={`${prefixCls}-ite...
)); const rowsArr: any[] = []; for (let i = 0; i < rowCount; i++) {
random_line_split
EmailController.py
import logging # Provides access to logging api. import smtplib class EmailController: def __init__(self, username, password, server, port, sender_name): self.logger = logging.getLogger(__name__) self.username = username self.password = password self.server = server self.p...
self.logger.debug("Successfully sent.") except smtplib.SMTPException: self.logger.error("Failed to send.") return False server.quit() return True # end EmailController
self.logger.debug("Trying smtp...") server = smtplib.SMTP(self.server, self.port) self.logger.debug("Trying ehlo...") server.ehlo() self.logger.debug("Trying starttls...") server.starttls() self.logger.debug("Trying login...") server.login(self.username, self.p...
identifier_body
EmailController.py
import logging # Provides access to logging api. import smtplib class EmailController: def __init__(self, username, password, server, port, sender_name): self.logger = logging.getLogger(__name__) self.username = username self.password = password self.server = server self.p...
def sendEmail(self, send_to, subject, text): self.logger.debug("Trying smtp...") server = smtplib.SMTP(self.server, self.port) self.logger.debug("Trying ehlo...") server.ehlo() self.logger.debug("Trying starttls...") server.starttls() self.logger.debug("Tr...
return def __del__(self): return
random_line_split
EmailController.py
import logging # Provides access to logging api. import smtplib class EmailController: def
(self, username, password, server, port, sender_name): self.logger = logging.getLogger(__name__) self.username = username self.password = password self.server = server self.port = port self.sender_name = sender_name return def __del__(self): return ...
__init__
identifier_name
widget_services_storage_mock.js
/** * Copyright 2016 aixigo AG * Released under the MIT license. * http://laxarjs.org/license
*/ /** * Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection. * * @module widget_services_storage_mock */ import { create as createGlobalStorageMock } from './storage_mock'; /** * Creates a mock for the `axStorage` injection of a widget. * * @return {AxS...
random_line_split
widget_services_storage_mock.js
/** * Copyright 2016 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ /** * Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection. * * @module widget_services_storage_mock */ import { create as createGlobalStorageMock } from './st...
() { const globalStorageMock = createGlobalStorageMock(); const namespace = 'mock'; const local = globalStorageMock.getLocalStorage( namespace ); const session = globalStorageMock.getSessionStorage( namespace ); /** * The AxStorageMock provides the same API as AxStorage, with the additional proper...
create
identifier_name
widget_services_storage_mock.js
/** * Copyright 2016 aixigo AG * Released under the MIT license. * http://laxarjs.org/license */ /** * Allows to instantiate a mock implementations of {@link AxStorage}, compatible to the "axStorage" injection. * * @module widget_services_storage_mock */ import { create as createGlobalStorageMock } from './st...
/** * Provides access to the backing stores for `local` and `session` storage. * * Contains `local` and `session` store properties. The stores are plain objects whose properties * reflect any setItem/removeItem operations. When properties are set on a store, they are observed * ...
{ const globalStorageMock = createGlobalStorageMock(); const namespace = 'mock'; const local = globalStorageMock.getLocalStorage( namespace ); const session = globalStorageMock.getSessionStorage( namespace ); /** * The AxStorageMock provides the same API as AxStorage, with the additional property ...
identifier_body
admin-stats-mints.component.ts
import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { UserComponent as User } from '../../../services/user.service'; @Component({ templateUrl: '../html/admin-stats-mints.component.html' }) export class AdminStatsMintsComponent { public list:any=[]; constr...
'nb': i, 'drachma': i*production*(1+4*(i-bonusNb)/100) }); } this.list.push({ 'nb': max, 'drachma': max*production*(1+5*(max-bonusNb)/100) }); } }
} for(let i=bonusNb+1;i<max;i++) { this.list.push({
random_line_split
admin-stats-mints.component.ts
import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { UserComponent as User } from '../../../services/user.service'; @Component({ templateUrl: '../html/admin-stats-mints.component.html' }) export class AdminStatsMintsComponent { public list:any=[]; constr...
for(let i=bonusNb+1;i<max;i++) { this.list.push({ 'nb': i, 'drachma': i*production*(1+4*(i-bonusNb)/100) }); } this.list.push({ 'nb': max, 'drachma': max*production*(1+5*(max-bonusNb)/100) }); } }
{ this.list.push({ 'nb': i, 'drachma': i*production }); }
conditional_block
admin-stats-mints.component.ts
import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { UserComponent as User } from '../../../services/user.service'; @Component({ templateUrl: '../html/admin-stats-mints.component.html' }) export class AdminStatsMintsComponent { public list:any=[];
(public user: User, public translate: TranslateService) { let production = 4200; let max = 100; let bonusNb:number = 80; for(let i=1;i<=bonusNb;i++) { this.list.push({ 'nb': i, 'drachma': i*production }); } for(let i=bonusNb+1;i<max;i++) { this.list.pu...
constructor
identifier_name
admin-stats-mints.component.ts
import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { UserComponent as User } from '../../../services/user.service'; @Component({ templateUrl: '../html/admin-stats-mints.component.html' }) export class AdminStatsMintsComponent { public list:any=[]; constr...
'nb': max, 'drachma': max*production*(1+5*(max-bonusNb)/100) }); } }
{ let production = 4200; let max = 100; let bonusNb:number = 80; for(let i=1;i<=bonusNb;i++) { this.list.push({ 'nb': i, 'drachma': i*production }); } for(let i=bonusNb+1;i<max;i++) { this.list.push({ 'nb': i, 'drachma': i*production*(1...
identifier_body
project-settings.page.ts
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class BellowsProjectSettingsPage { private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('settings-dropdown-button')); pr...
noticeList = element.all(by.repeater('notice in $ctrl.notices()')); firstNoticeCloseButton = this.noticeList.first().element(by.buttonText('×')); tabDivs = element.all(by.className('tab-pane')); activePane = element(by.css('div.tab-pane.active')); /* Would like to use id locators, but the pui-tab direct...
{ this.projectsPage.get(); this.projectsPage.clickOnProject(projectName); browser.wait(ExpectedConditions.visibilityOf(this.settingsMenuLink), this.conditionTimeout); this.settingsMenuLink.click(); browser.wait(ExpectedConditions.visibilityOf(this.projectSettingsLink), this.conditionTimeout); th...
identifier_body
project-settings.page.ts
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class
{ private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('settings-dropdown-button')); projectSettingsLink = element(by.id('dropdown-project-settings')); // Get the projectSettings for project projectName get(projectName: string) { this.p...
BellowsProjectSettingsPage
identifier_name
project-settings.page.ts
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class BellowsProjectSettingsPage {
private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('settings-dropdown-button')); projectSettingsLink = element(by.id('dropdown-project-settings')); // Get the projectSettings for project projectName get(projectName: string) { this.proj...
random_line_split
labels.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom, self}; use std::iter; use std::ops::{Index, Range}; use std::path::Path; use byteorder::{BigEndian, ReadBytesExt}; use cast::From as _0; use linalg::prelude::*; /// Labels corresponding to a set of images pub struct Labels { data: Vec<u8>, num_classes: u3...
let num_classes = u32::from_(*buf.iter().max().unwrap_or(&0)) + 1; Ok(Labels { data: buf, num_classes: num_classes, size: end - start, }) } /// Returns the number of classes pub fn num_classes(&self) -> u32 { self.num_classes } ...
{ /// Magic number expected in the header const MAGIC: u32 = 2049; assert!(start < end); let mut file = try!(File::open(path)); // Parse the header: MAGIC NLABELS assert_eq!(try!(file.read_u32::<BigEndian>()), MAGIC); let nlabels = try!(file.read_u32::<BigEndia...
identifier_body
labels.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom, self}; use std::iter; use std::ops::{Index, Range}; use std::path::Path; use byteorder::{BigEndian, ReadBytesExt}; use cast::From as _0; use linalg::prelude::*; /// Labels corresponding to a set of images pub struct Labels { data: Vec<u8>, num_classes: u3...
for (mut r, &label) in m.rows_mut().zip(&self.data) { r[u32::from_(label)] = 1.; } m } } impl Index<u32> for Labels { type Output = u8; fn index(&self, i: u32) -> &u8 { &self.data[usize::from_(i)] } }
random_line_split
labels.rs
use std::fs::File; use std::io::{Read, Seek, SeekFrom, self}; use std::iter; use std::ops::{Index, Range}; use std::path::Path; use byteorder::{BigEndian, ReadBytesExt}; use cast::From as _0; use linalg::prelude::*; /// Labels corresponding to a set of images pub struct Labels { data: Vec<u8>, num_classes: u3...
<P>(path: P, subset: Range<u32>) -> io::Result<Labels> where P: AsRef<Path> { Labels::load_(path.as_ref(), subset) } fn load_(path: &Path, Range { start, end }: Range<u32>) -> io::Result<Labels> { /// Magic number expected in the header const MAGIC: u32 = 2049; assert!(start < ...
load
identifier_name
0014_auto_20181122_1211.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-22 11:11 from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('WorkflowEngine', '0001_initial'), ('tags', '0013_auto_20180925_1142'), ] operations = [ migrations.AddField( model_name='tag', name='task', field=models.ForeignKey(null=True, on_delete=django.db.models.d...
Migration
identifier_name
0014_auto_20181122_1211.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-22 11:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('WorkflowEngine', '0001_initial'), ('tags', '0013_auto_20180925_1142'), ] operation...
model_name='tagstructure', name='structure_unit', field=models.ForeignKey(limit_choices_to={'structure__is_template': False}, null=True, on_delete=django.db.models.deletion.PROTECT, to='tags.StructureUnit'), ), ]
model_name='tag', name='task', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tags', to='WorkflowEngine.ProcessTask'), ), migrations.AddField(
random_line_split
0014_auto_20181122_1211.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-11-22 11:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('WorkflowEngine', '0001_initial'), ('tags', '0013_auto_20180925_1142'), ] operations = [ migrations.AddField( model_name='tag', name='task', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_nam...
identifier_body
content_length.rs
use std::fmt; use header::{Header, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) /// /// When a message does not have a `Transfer-Encoding` header field, a /// Content-Length header field can provide the anticipated size, as a /// decimal number of ...
/// /// let mut headers = Headers::new(); /// headers.set(ContentLength(1024u64)); /// ``` #[derive(Clone, Copy, Debug, PartialEq)] pub struct ContentLength(pub u64); impl Header for ContentLength { #[inline] fn header_name() -> &'static str { "Content-Length" } fn parse_header(raw: &[Vec<u8>]...
/// * `3495` /// /// # Example /// ``` /// use hyper::header::{Headers, ContentLength};
random_line_split
content_length.rs
use std::fmt; use header::{Header, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) /// /// When a message does not have a `Transfer-Encoding` header field, a /// Content-Length header field can provide the anticipated size, as a /// decimal number of ...
() -> &'static str { "Content-Length" } fn parse_header(raw: &[Vec<u8>]) -> ::Result<ContentLength> { // If multiple Content-Length headers were sent, everything can still // be alright if they all contain the same value, and all parse // correctly. If not, then it's an error. ...
header_name
identifier_name
content_length.rs
use std::fmt; use header::{Header, parsing}; /// `Content-Length` header, defined in /// [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.2) /// /// When a message does not have a `Transfer-Encoding` header field, a /// Content-Length header field can provide the anticipated size, as a /// decimal number of ...
} impl fmt::Display for ContentLength { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } __hyper__deref!(ContentLength => u64); __hyper_generate_header_serialization!(ContentLength); __hyper__tm!(ContentLength, tests { // Testcase from RFC ...
{ fmt::Display::fmt(&self.0, f) }
identifier_body
cordova.js
/* global device: false */ /* global PushNotification: false */ var getService = function() { if (/android/i.test(device.platform)) { return 'gcm'; } else if (/ios/i.test(device.platform)) { return 'apn'; } else if (/win/i.test(device.platform)) { return 'mpns'; } return 'unknown'; }; /** * htt...
() { if (this.debug) { console.log(...arguments); } } setBadge(count) { this.once('ready', () => { if (/ios/i.test(device.platform)) { this.log('Push.setBadge:', count); // xxx: at the moment only supported on iOS this.push.setApplicationIconBadgeNumber(() => { ...
log
identifier_name
cordova.js
/* global device: false */ /* global PushNotification: false */ var getService = function() { if (/android/i.test(device.platform)) { return 'gcm'; } else if (/ios/i.test(device.platform)) { return 'apn'; } else if (/win/i.test(device.platform)) { return 'mpns'; } return 'unknown'; }; /** * htt...
Push = new PushHandle();
}
random_line_split
cordova.js
/* global device: false */ /* global PushNotification: false */ var getService = function() { if (/android/i.test(device.platform)) { return 'gcm'; } else if (/ios/i.test(device.platform)) { return 'apn'; } else if (/win/i.test(device.platform)) { return 'mpns'; } return 'unknown'; }; /** * htt...
var token = { [getService()]: data.registrationId }; this.log('Push.Token:', token); this.emitState('token', token); } this.emitState('registration', ...arguments); }); this.push.on('notification', (dat...
{ if (!this.configured) { this.log('Push.Configure:', options); this.configured = true; Meteor.startup(() => { if (typeof PushNotification !== 'undefined') { this.push = PushNotification.init(options); this.push.on('registration', (data) => { // xxx: ...
identifier_body
cordova.js
/* global device: false */ /* global PushNotification: false */ var getService = function() { if (/android/i.test(device.platform)) { return 'gcm'; } else if (/ios/i.test(device.platform)) { return 'apn'; } else if (/win/i.test(device.platform)) { return 'mpns'; } return 'unknown'; }; /** * htt...
// Emit sound event if (data.sound) { this.emit('sound', data); } // Emit badge event if (typeof data.count !== 'undefined') { this.log('Push.SettingBadge:', data.count); this.setBadge(data.count); thi...
{ this.emit('alert', data); }
conditional_block
sw-CD.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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
(n: number): number { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } export default [ 'sw-CD', [['am', 'pm'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Jumapili', 'Jumatatu', '...
plural
identifier_name
sw-CD.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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
export default [ 'sw-CD', [['am', 'pm'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], u, u ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'F...
{ let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; }
identifier_body
sw-CD.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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; fun...
export default [ 'sw-CD', [['am', 'pm'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Jumapili', 'Jumatatu', 'Jumanne', 'Jumatano', 'Alhamisi', 'Ijumaa', 'Jumamosi'], u, u ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Fe...
if (i === 1 && v === 0) return 1; return 5; }
random_line_split
Devloader.py
""" Here, we need some documentation... """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import types import threading import time import six from DIRAC import gLogger from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton @...
for stuff in self.__stuffToClose: try: self.__log.always("Closing %s" % stuff) sys.stdout.flush() stuff.close() except Exception: gLogger.exception("Could not close %s" % stuff) python = sys.executable os.execl(python, python, * sys.argv) def bootstrap(self): ...
return False def __restart(self): self.__reloaded = True
random_line_split
Devloader.py
""" Here, we need some documentation... """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import types import threading import time import six from DIRAC import gLogger from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton @...
(self, path): try: modified = os.stat(path).st_mtime except Exception: return if path not in self.__modifyTimes: self.__modifyTimes[path] = modified return if self.__modifyTimes[path] != modified: self.__log.always("File system changed (%s). Restarting..." % (path)) s...
__checkFile
identifier_name
Devloader.py
""" Here, we need some documentation... """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import types import threading import time import six from DIRAC import gLogger from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton @...
self.__reloadTask = threading.Thread(target=self.__reloadOnUpdate) self.__reloadTask.setDaemon(1) self.__reloadTask.start() def __reloadOnUpdate(self): while True: time.sleep(1) if self.__reloaded: return for modName in sys.modules: modObj = sys.modules[modName] ...
return True
conditional_block
Devloader.py
""" Here, we need some documentation... """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import types import threading import time import six from DIRAC import gLogger from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton @...
def __restart(self): self.__reloaded = True for stuff in self.__stuffToClose: try: self.__log.always("Closing %s" % stuff) sys.stdout.flush() stuff.close() except Exception: gLogger.exception("Could not close %s" % stuff) python = sys.executable os.execl...
if os.path.isfile(fp): self.__watchedFiles.append(fp) return True return False
identifier_body
omni.py
""" Methods for importing data from the OMNI. """ from heliopy.data import cdasrest def _docstring(identifier, description): return cdasrest._docstring(identifier, 'O', description) def _omni(starttime, endtime, identifier, intervals='monthly', warn_missing_units=True): """ Generic method for ...
(starttime, endtime): identifier = 'OMNI_HRO2_5MIN' return _omni(starttime, endtime, identifier, warn_missing_units=False, intervals='monthly') hro2_1min.__doc__ = _docstring( 'OMNI_HRO2_5MIN', '5 minute averaged definitive multi-spacecraft ' 'interplanetary paramete...
hro2_5min
identifier_name
omni.py
""" Methods for importing data from the OMNI. """ from heliopy.data import cdasrest def _docstring(identifier, description):
def _omni(starttime, endtime, identifier, intervals='monthly', warn_missing_units=True): """ Generic method for downloading OMNI data. """ dl = cdasrest.CDASDwonloader('omni', identifier, 'omni', warn_missing_units=warn_missing_units) # Override interval...
return cdasrest._docstring(identifier, 'O', description)
identifier_body
omni.py
""" Methods for importing data from the OMNI. """ from heliopy.data import cdasrest def _docstring(identifier, description): return cdasrest._docstring(identifier, 'O', description) def _omni(starttime, endtime, identifier, intervals='monthly', warn_missing_units=True): """ Generic method for ...
return dl.load(starttime, endtime) # Actual download functions start here def h0_mrg1hr(starttime, endtime): identifier = 'OMNI2_H0_MRG1HR' return _omni(starttime, endtime, identifier, warn_missing_units=False, intervals='yearly') h0_mrg1hr.__doc__ = _docstring( 'OMNI2_H0_MRG1HR', ...
dl.intervals = dl.intervals_yearly
conditional_block
omni.py
""" Methods for importing data from the OMNI. """ from heliopy.data import cdasrest def _docstring(identifier, description): return cdasrest._docstring(identifier, 'O', description) def _omni(starttime, endtime, identifier, intervals='monthly', warn_missing_units=True): """ Generic method for ...
dl.intervals = dl.intervals_monthly elif intervals == 'yearly': dl.intervals = dl.intervals_yearly return dl.load(starttime, endtime) # Actual download functions start here def h0_mrg1hr(starttime, endtime): identifier = 'OMNI2_H0_MRG1HR' return _omni(starttime, endtime, identifier, wa...
if intervals == 'daily': dl.intervals = dl.intervals_daily elif intervals == 'monthly':
random_line_split
test_inlinequeryresultvideo.py
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2016 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by ...
'description': self.description, 'input_message_content': self.input_message_content.to_dict(), 'reply_markup': self.reply_markup.to_dict(), } def test_video_de_json(self): video = telegram.InlineQueryResultVideo.de_json(self.json_dict) self.assertEqual(...
random_line_split
test_inlinequeryresultvideo.py
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2016 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by ...
'type': self.type, 'id': self.id, 'video_url': self.video_url, 'mime_type': self.mime_type, 'video_width': self.video_width, 'video_height': self.video_height, 'video_duration': self.video_duration, 'thumb_url': self.thumb_u...
"""This object represents Tests for Telegram InlineQueryResultVideo.""" def setUp(self): self.id = 'id' self.type = 'video' self.video_url = 'video url' self.mime_type = 'mime type' self.video_width = 10 self.video_height = 15 self.video_duration = 15 ...
identifier_body
test_inlinequeryresultvideo.py
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2016 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by ...
(BaseTest, unittest.TestCase): """This object represents Tests for Telegram InlineQueryResultVideo.""" def setUp(self): self.id = 'id' self.type = 'video' self.video_url = 'video url' self.mime_type = 'mime type' self.video_width = 10 self.video_height = 15 ...
InlineQueryResultVideoTest
identifier_name
test_inlinequeryresultvideo.py
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2016 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by ...
unittest.main()
conditional_block
router.rs
use std::fmt; use std::error::Error; use std::fmt::Display; use std::io::Read; use std::io; use tiny_http::{Request, Method, StatusCode}; use rustc_serialize::json; use rustc_serialize::json::Json; use url_parser; use url_parser::UrlResource; use std::io::Cursor; use tiny_http::Response; use api; use context::Con...
() { let response = request_router(&Method::Post, UrlResource::from_resource("/foo").unwrap()); assert!(http::response_string(response) == http::response_string(ok("foobar"))); } #[test] fn test_vector_match() { let v = vec!("foo", "bar", "baz"); match ("fish", &v[..]) { (_, []) ...
test_routing
identifier_name
router.rs
use std::fmt; use std::error::Error; use std::fmt::Display; use std::io::Read; use std::io; use tiny_http::{Request, Method, StatusCode}; use rustc_serialize::json; use rustc_serialize::json::Json; use url_parser; use url_parser::UrlResource; use std::io::Cursor; use tiny_http::Response; use api; use context::Con...
} impl From<json::ParserError> for RequestError { fn from(err: json::ParserError) -> RequestError { RequestError::JsonParseError(err) } } impl From<url_parser::UrlParseError> for RequestError { fn from(err: url_parser::UrlParseError) -> RequestError { RequestError::UrlParseError(err) } ...
{ RequestError::ReadError(err) }
identifier_body
router.rs
use std::fmt; use std::error::Error; use std::fmt::Display; use std::io::Read; use std::io; use tiny_http::{Request, Method, StatusCode}; use rustc_serialize::json; use rustc_serialize::json::Json; use url_parser; use url_parser::UrlResource; use std::io::Cursor; use tiny_http::Response; use api; use context::Cont...
RequestError::UrlParseError(ref err) => err.description(), RequestError::UnknownResource => "Unknown url", RequestError::UnsupportedMethod => "Unsupported Method", } } } impl From<io::Error> for RequestError { fn from(err: io::Error) -> RequestError { RequestE...
match *self { RequestError::ReadError(ref err) => err.description(), RequestError::JsonParseError(ref err) => err.description(),
random_line_split
lib.rs
//! This library implements basic processing of JavaScript sourcemaps. //! //! # Installation //! //! The crate is called sourcemap and you can depend on it via cargo: //! //! ```toml //! [dependencies] //! sourcemap = "*" //! ``` //! //! If you want to use the git version: //! //! ```toml //! [dependencies.sourcemap] ...
//! }"; //! let sm = SourceMap::from_reader(input).unwrap(); //! let token = sm.lookup_token(0, 0).unwrap(); // line-number and column //! println!("token: {}", token); //! ``` //! //! # Features //! //! Functionality of the crate can be turned on and off by feature flags. This is the //! current list of feature flags...
//! \"sources\":[\"coolstuff.js\"], //! \"names\":[\"x\",\"alert\"], //! \"mappings\":\"AAAA,GAAIA,GAAI,EACR,IAAIA,GAAK,EAAG,CACVC,MAAM\"
random_line_split
steps.d.ts
type ICodeceptCallback = (i: CodeceptJS.I, ...steps: any) => void; declare const actor: () => CodeceptJS.I; declare const Feature: (string: string) => void; declare const Scenario: (string: string, callback: ICodeceptCallback) => any; declare const Before: (callback: ICodeceptCallback) => void; declare const After: (c...
declare namespace CodeceptJS { export interface I { defineTimeout: (timeouts) => any; amOnPage: (amOnPage) => any; click: (click) => any; doubleClick: (doubleClick) => any; rightClick: (rightClick) => any; appendField: (appendField) => any; selectOption: (selectOption) => any; attachFi...
declare const within: (selector: string, callback: Function) => void;
random_line_split
test_session.py
import datetime from mock import patch from pretend import stub from gurtel import session def test_annotates_request(): """Annotates request with ``session`` property.""" request = stub( cookies={}, app=stub(secret_key='secret', is_ssl=True, config={}), ) session.session_middle...
(mock_save_cookie): """Calls ``save_cookie`` on response.""" request = stub( cookies={}, app=stub(secret_key='secret', is_ssl=True, config={}), ) response = stub() session.session_middleware(request, lambda req: response) mock_save_cookie.assert_called_once_with( re...
test_sets_cookie_on_response
identifier_name
test_session.py
import datetime from mock import patch from pretend import stub from gurtel import session def test_annotates_request(): """Annotates request with ``session`` property.""" request = stub( cookies={}, app=stub(secret_key='secret', is_ssl=True, config={}), ) session.session_middle...
mock_save_cookie.assert_called_once_with( response, httponly=True, secure=True) @patch.object(session.JSONSecureCookie, 'save_cookie') @patch.object(session.timezone, 'now') def test_can_set_expiry(mock_now, mock_save_cookie): """Calls ``save_cookie`` on response with expiry date, if configured.""" ...
session.session_middleware(request, lambda req: response)
random_line_split
test_session.py
import datetime from mock import patch from pretend import stub from gurtel import session def test_annotates_request():
@patch.object(session.JSONSecureCookie, 'save_cookie') def test_sets_cookie_on_response(mock_save_cookie): """Calls ``save_cookie`` on response.""" request = stub( cookies={}, app=stub(secret_key='secret', is_ssl=True, config={}), ) response = stub() session.session_middlewar...
"""Annotates request with ``session`` property.""" request = stub( cookies={}, app=stub(secret_key='secret', is_ssl=True, config={}), ) session.session_middleware(request, lambda req: None) assert request.session.secret_key == 'secret'
identifier_body
assign_ops2.rs
#[allow(unused_assignments)] #[warn(clippy::misrefactored_assign_op, clippy::assign_op_pattern)] fn main() { let mut a = 5; a += a + 1; a += 1 + a; a -= a - 1; a *= a * 99; a *= 42 * a; a /= a / 2; a %= a % 5; a &= a & 1; a *= a * a; a = a * a * a; a = a * 42 * a; a =...
} fn cow_add_assign() { use std::borrow::Cow; let mut buf = Cow::Owned(String::from("bar")); let cows = Cow::Borrowed("foo"); // this can be linted buf = buf + cows.clone(); // this should not as cow<str> Add is not commutative buf = cows + buf; println!("{}", buf); }
{ *self = *self * rhs }
identifier_body
assign_ops2.rs
#[allow(unused_assignments)] #[warn(clippy::misrefactored_assign_op, clippy::assign_op_pattern)] fn main() { let mut a = 5; a += a + 1; a += 1 + a; a -= a - 1; a *= a * 99; a *= 42 * a; a /= a / 2; a %= a % 5; a &= a & 1; a *= a * a; a = a * a * a; a = a * 42 * a; a =...
() { use std::borrow::Cow; let mut buf = Cow::Owned(String::from("bar")); let cows = Cow::Borrowed("foo"); // this can be linted buf = buf + cows.clone(); // this should not as cow<str> Add is not commutative buf = cows + buf; println!("{}", buf); }
cow_add_assign
identifier_name
assign_ops2.rs
#[allow(unused_assignments)] #[warn(clippy::misrefactored_assign_op, clippy::assign_op_pattern)] fn main() { let mut a = 5; a += a + 1; a += 1 + a; a -= a - 1; a *= a * 99; a *= 42 * a; a /= a / 2; a %= a % 5; a &= a & 1; a *= a * a; a = a * a * a; a = a * 42 * a; a =...
#[derive(Copy, Clone, Debug, PartialEq)] pub struct Wrap(i64); impl Mul<i64> for Wrap { type Output = Self; fn mul(self, rhs: i64) -> Self { Wrap(self.0 * rhs) } } impl MulAssign<i64> for Wrap { fn mul_assign(&mut self, rhs: i64) { *self = *self * rhs } } fn cow_add_assign() { ...
random_line_split
cacheWrapper.ts
/** * 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...
const result = fn(...args); cache.set(key, result); return result; };
{ return cache.get(key); }
conditional_block
cacheWrapper.ts
/** * 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
* * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the L...
* to you 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
random_line_split
main.js
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player')
var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update() { if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { co...
random_line_split
main.js
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function
() { if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0') } else if(x < 0 ) { var...
update
identifier_name
main.js
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update() { if(keydown.space) { player.shoot(); }...
if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0') } else if(x < 0 ) { var p = wWidth + x - pWidth; var t = p + 'px' player.css('left', t) } else { player.css('left', '+=10'); } } ...
{ console.log('go left') player.css('left', '-=10'); }
conditional_block
main.js
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update()
} else if(x < 0 ) { var p = wWidth + x - pWidth; var t = p + 'px' player.css('left', t) } else { player.css('left', '+=10'); } } } $('') })
{ if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0')
identifier_body
RedisFactory.py
from JumpScale9 import j redisFound = False try: from .Redis import Redis from .RedisQueue import RedisQueue from redis._compat import nativestr # import itertools import socket redisFound = True except: pass import os import time # import sys from JumpScale9 import tcpPortConnectionTest f...
def core_check(self): if not self.core_running(): self.core_start() return self._running def core_start(self, timeout=20): """ starts a redis instance in separate ProcessLookupError standard on $tmpdir/redis.sock """ if j.core.platform...
return self._running
random_line_split
RedisFactory.py
from JumpScale9 import j redisFound = False try: from .Redis import Redis from .RedisQueue import RedisQueue from redis._compat import nativestr # import itertools import socket redisFound = True except: pass import os import time # import sys from JumpScale9 import tcpPortConnectionTest f...
key = unixsocket if key not in self._redis or not fromcache: if unixsocket is None: self._redis[key] = Redis(ipaddr, port, password=password, ssl=ssl, ssl_certfile=ssl_certfile, ssl_keyfile=ssl_keyfile, **args) else: self._redis[key] = Redis(u...
""" get an instance of redis client, store it in cache so we could easily retrieve it later :param ipaddr: used to form the key when no unixsocket :param port: used to form the key when no unixsocket :param fromcache: if False, will create a new one instead of checking cache :pa...
identifier_body
RedisFactory.py
from JumpScale9 import j redisFound = False try: from .Redis import Redis from .RedisQueue import RedisQueue from redis._compat import nativestr # import itertools import socket redisFound = True except: pass import os import time # import sys from JumpScale9 import tcpPortConnectionTest f...
(self, client): client.response_callbacks['HDEL'] = lambda r: r and nativestr(r) == 'OK' def _set_patch(self, client): client.response_callbacks['SET'] = lambda r: r def getQueue(self, ipaddr, port, name, namespace="queues", fromcache=True): """ get an instance of redis queue, ...
_ardb_patch
identifier_name
RedisFactory.py
from JumpScale9 import j redisFound = False try: from .Redis import Redis from .RedisQueue import RedisQueue from redis._compat import nativestr # import itertools import socket redisFound = True except: pass import os import time # import sys from JumpScale9 import tcpPortConnectionTest f...
time.sleep(2) else: raise j.exceptions.Timeout("Couldn't start redis server")
break
conditional_block
graph.py
import os import json from subprocess import check_output, CalledProcessError #Constants _TREE_PATH="data/graph/" def renderGraph(query): """ Returns the path to a svg file that contains the graph render of the query. Creates the svg file itself if it does not already exist. "...
'ymin':-10, 'ymax':10, 'xlabel':"x", 'ylabel':"y", } for i in paramsIn: if i!='xlabel' and i !='ylabel': params[i]=int(paramsIn[i]) else: params[i]=paramsIn[i] print params print fn try: check_output("./to_graph.sh {0} {...
random_line_split
graph.py
import os import json from subprocess import check_output, CalledProcessError #Constants _TREE_PATH="data/graph/" def renderGraph(query): """ Returns the path to a svg file that contains the graph render of the query. Creates the svg file itself if it does not already exist. "...
except CalledProcessError: return False return True def handleTeXRenderError(errorMsg): """ Handles an error encountered while attempting to render a TeX string """ print errorMsg return "assets/img/error.png"
""" Renders a graph in query to a svg in targetDir named name. Return true if successful, false if not. """ params={ 'xmin':-10, 'xmax':10, 'ymin':-10, 'ymax':10, 'xlabel':"x", 'ylabel':"y", } for i in paramsIn: if i!='xlabel' and i !='ylab...
identifier_body
graph.py
import os import json from subprocess import check_output, CalledProcessError #Constants _TREE_PATH="data/graph/" def
(query): """ Returns the path to a svg file that contains the graph render of the query. Creates the svg file itself if it does not already exist. """ #Compute the hash of the query string qhash = hashFunc(query) if (not os.path.exists(_TREE_PATH+str(qhash))): ...
renderGraph
identifier_name