file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
react-swipe-tests.tsx
import * as React from "react"; import * as ReactSwipe from "react-swipe"; class ReactSwipeTest extends React.PureComponent { private swipeComponent: ReactSwipe | null = null; private onPrev: React.MouseEventHandler<HTMLButtonElement> = () => { if (this.swipeComponent != null) { this.swipe...
() { const swipeOptions: SwipeOptions = { auto: 12, disableScroll: true, stopPropagation: true }; const style: ReactSwipe.Style = { child: { backgroundColor: "yellow" }, container: { backgrou...
render
identifier_name
react-swipe-tests.tsx
import * as React from "react"; import * as ReactSwipe from "react-swipe"; class ReactSwipeTest extends React.PureComponent { private swipeComponent: ReactSwipe | null = null; private onPrev: React.MouseEventHandler<HTMLButtonElement> = () => { if (this.swipeComponent != null) { this.swipe...
} private onSlideToStart: React.MouseEventHandler<HTMLButtonElement> = () => { if (this.swipeComponent != null) { const lastSlide = this.swipeComponent.getNumSlides() - 1; this.swipeComponent.slide(lastSlide, 1000); } } private onGetCurrentPosition: React.Mouse...
{ this.swipeComponent.next(); }
conditional_block
FilterTest.py
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
# met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in...
# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are
random_line_split
FilterTest.py
########################################################################## # # Copyright (c) 2013, 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: # # * Redistrib...
f = GafferImage.Filter.create( name ) self.assertTrue( f.typeName(), name+"Filter" )
conditional_block
FilterTest.py
########################################################################## # # Copyright (c) 2013, 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: # # * Redistrib...
def testDefaultFilter( self ) : filters = GafferImage.Filter.filters() default = GafferImage.Filter.defaultFilter() self.assertTrue( default in filters ) def testFilterList( self ) : filters = GafferImage.Filter.filters() self.assertTrue( len(filters) == 9 ) self.assertTrue( "Box" in filters ) self.asse...
identifier_body
FilterTest.py
########################################################################## # # Copyright (c) 2013, 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: # # * Redistrib...
( self ) : filters = GafferImage.Filter.filters() for name in filters : f = GafferImage.Filter.create( name ) self.assertTrue( f.typeName(), name+"Filter" )
testCreators
identifier_name
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
( cx: *mut JSContext, mut result: MutableHandleObject, done: bool, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyOrValueResult::empty(); dict.done = done; dict.value.set(value.get()); rooted!(in(cx) let mut dict_value = UndefinedValue()); unsafe { dict.to_...
dict_return
identifier_name
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
, } }; self.index.set(index + 1); result.map(|_| NonNull::new(rval.get()).expect("got a null pointer")) } } fn dict_return( cx: *mut JSContext, mut result: MutableHandleObject, done: bool, value: HandleValue, ) -> Fallible<()> { let mut dict = IterableKeyOrVa...
{ rooted!(in(cx) let mut key = UndefinedValue()); unsafe { self.iterable .get_key_at_index(index) .to_jsval(cx, key.handle_mut()); self.iterable .ge...
conditional_block
iterable.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 https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. use ...
type_: IteratorType, index: Cell<u32>, } impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new( iterable: &T, type_: IteratorType, wrap: unsafe fn(*mut JSContext, &GlobalScope, Box...
reflector: Reflector, iterable: Dom<T>,
random_line_split
config.js
'use strict'
'appID': '261938654297222', 'appSecret': 'cd8d0bf4ce75ae5e24be29970b79876f', 'callbackUrl': '/login/facebook/callback/' } config.server = { 'port': process.env.PORT || 3000, 'env': process.env.NODE_ENV || 'dev', 'dbUrl': process.env.MONGODB_URI || 'mongodb://localhost:27017/minihero', 'sessionSecret': 'M...
var config = {} config.facebook = {
random_line_split
imtools.py
#!/usr/bin/env python import logging import inspect import numpy as np #from matplotlib import _cntr as cntr #from contours.core import shapely_formatter as shapely_fmt #from contours.quad import QuadContourGenerator from astropy.coordinates import Angle from astropy import constants as c from astropy import wcs fro...
(xvert, yvert): """ Compute twice the area of the triangle defined by points using the determinant formula. Parameters ---------- xvert : array A vector of nodal x-coords. yvert : array A vector of nodal y-coords. Returns ------- area : float Twice the a...
_det
identifier_name
imtools.py
#!/usr/bin/env python import logging import inspect import numpy as np #from matplotlib import _cntr as cntr #from contours.core import shapely_formatter as shapely_fmt #from contours.quad import QuadContourGenerator from astropy.coordinates import Angle from astropy import constants as c from astropy import wcs fro...
# If snear = True: Dist to nearest side < nearest vertex # If snear = False: Dist to nearest vertex < nearest side snear = np.ma.masked_all(xpoint.shape, dtype=bool) # Initialize arrays mindst = np.ones_like(xpoint, dtype=float) * np.inf j = np.ma.masked_all(xpoint.sha...
raise IndexError('x and y must be equally sized.')
conditional_block
imtools.py
#!/usr/bin/env python import logging import inspect import numpy as np #from matplotlib import _cntr as cntr #from contours.core import shapely_formatter as shapely_fmt #from contours.quad import QuadContourGenerator from astropy.coordinates import Angle from astropy import constants as c from astropy import wcs fro...
def make_mask(self, shape, **kwargs): """ Creates a mask of a given shape using the Polygon as boundaries. All points inside the Polygon will have a value of 1. :param shape: Shape of the output mask. :type shape: tuple :returns: Mask of the Polygon. ...
""" Check if point is inside a general polygon. An improved version of the algorithm of Nordbeck and Rydstedt. REF: SLOAN, S.W. (1985): A point-in-polygon program. Adv. Eng. Software, Vol 7, No. 1, pp 45-47. Parameters ---------- xpoint : array or float ...
identifier_body
imtools.py
#!/usr/bin/env python import logging import inspect import numpy as np #from matplotlib import _cntr as cntr #from contours.core import shapely_formatter as shapely_fmt #from contours.quad import QuadContourGenerator from astropy.coordinates import Angle from astropy import constants as c from astropy import wcs fro...
---------- x : array A sequence of nodal x-coords. y : array A sequence of nodal y-coords. """ def __init__(self, x, y): self.logger = logging.getLogger(__name__) self.logger.info("Creating Polygon") if len(x) != len(y): raise In...
Parameters
random_line_split
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * 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 ap...
{ zeros( 'abc' ); // $ExpectError zeros( true ); // $ExpectError zeros( false ); // $ExpectError zeros( null ); // $ExpectError zeros( [] ); // $ExpectError zeros( {} ); // $ExpectError zeros( ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsuppor...
{ zeros( 3 ); // $ExpectType number[] } // The compiler throws an error if the function is provided an argument which is not a number...
random_line_split
session.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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) any la...
} enum ErrorType { NotFound, Forbidden, } fn error(error: ErrorType, title: &str, message: &str, details: Option<&str>) -> ws::Response { let content = format!( include_str!("./error_tpl.html"), title=title, meta="", message=message, details=details.unwrap_or(""), version=version(), ); let res = mat...
{ Session { out: sender, handler: self.handler.clone(), skip_origin_validation: self.skip_origin_validation, self_origin: self.self_origin.clone(), authcodes_path: self.authcodes_path.clone(), file_handler: self.file_handler.clone(), } }
identifier_body
session.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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) any la...
{ pub content: &'static [u8], pub content_type: &'static str, } #[derive(Default)] pub struct Handler; impl Handler { pub fn handle(&self, _req: &str) -> Option<&File> { None } } } const HOME_DOMAIN: &'static str = "home.parity"; fn origin_is_allowed(self_origin: &str, header: Option<&[u8]>) -> boo...
File
identifier_name
session.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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) any la...
} } enum ErrorType { NotFound, Forbidden, } fn error(error: ErrorType, title: &str, message: &str, details: Option<&str>) -> ws::Response { let content = format!( include_str!("./error_tpl.html"), title=title, meta="", message=message, details=details.unwrap_or(""), version=version(), ); let res = m...
file_handler: self.file_handler.clone(), }
random_line_split
session.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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) any la...
res }) .unwrap_or(false) } else { false } }) }, _ => false } } fn add_headers(mut response: ws::Response, mime: &str) -> ws::Response { let content_len = format!("{}", response.len()); { let mut headers = response.headers_mut(); headers.push(("X-Frame-Options".into(), b"S...
{ warn!(target: "signer", "Couldn't save authorization codes to file."); }
conditional_block
popup.ts
'use strict'; module TourabuEx.popup { var setting = <HTMLFormElement>document.querySelector('#setting'); interface Setting { setting: {}; } function loadSetting() { storage.get('setting').done(function (s) { var k, el; for (k in (<Object>s)) { ...
if (mes.type === 'capture/enable') { $('#screenshot').show(); } }); // widget mode $('#start-widget').click(function () { chrome.runtime.sendMessage({ type: 'start/widget' }); }); }
$('#screenshot').show(); }
conditional_block
popup.ts
'use strict'; module TourabuEx.popup { var setting = <HTMLFormElement>document.querySelector('#setting'); interface Setting { setting: {}; } function loadSetting() {
loadSetting(); setting.addEventListener('change',() => { var selects = <NodeList>document.querySelectorAll('#notification select'), i: number, l = selects.length, select: HTMLOptionElement, s: Setting = { setting: {}}; for (i = 0; i < l; i++) { ...
storage.get('setting').done(function (s) { var k, el; for (k in (<Object>s)) { if (s.hasOwnProperty(k)) { el = <HTMLOptionElement>document.querySelector('#' + k); el.value = s[k]; } } }); }
identifier_body
popup.ts
'use strict'; module TourabuEx.popup { var setting = <HTMLFormElement>document.querySelector('#setting'); interface Setting { setting: {}; } function lo
{ storage.get('setting').done(function (s) { var k, el; for (k in (<Object>s)) { if (s.hasOwnProperty(k)) { el = <HTMLOptionElement>document.querySelector('#' + k); el.value = s[k]; } } }); }...
adSetting()
identifier_name
popup.ts
'use strict'; module TourabuEx.popup { var setting = <HTMLFormElement>document.querySelector('#setting'); interface Setting { setting: {}; } function loadSetting() { storage.get('setting').done(function (s) { var k, el; for (k in (<Object>s)) { ...
if (mes.type === 'capture/enable') { $('#screenshot').show(); } }); // widget mode $('#start-widget').click(function () { chrome.runtime.sendMessage({ type: 'start/widget' }); }); }
random_line_split
test_form.py
# -*- coding: utf-8 -*- from io import BytesIO import pytest from phi.request.form import FormRequest class TestFormRequest(object): @pytest.fixture def form_req(self): fr = FormRequest() fr.charset = "utf-8" return fr @pytest.mark.parametrize("body, content", [ ( ...
(self, body, content, form_req): stream = BytesIO(body.encode("utf-8")) stream.seek(0) form_req._content_stream = stream form_req.content_length = len(body) assert form_req._get_body() == content
test_body
identifier_name
test_form.py
# -*- coding: utf-8 -*- from io import BytesIO import pytest from phi.request.form import FormRequest class TestFormRequest(object): @pytest.fixture def form_req(self): fr = FormRequest() fr.charset = "utf-8" return fr
), ( "name=test&blah=asdfdasf+&check=on", {"blah": "asdfdasf ", "name": "test", "check": "on"} ), ]) def test_body(self, body, content, form_req): stream = BytesIO(body.encode("utf-8")) stream.seek(0) form_req._content_stream = stream ...
@pytest.mark.parametrize("body, content", [ ( "name=test&blah=asdfdasf+&check=on", {"blah": "asdfdasf ", "name": "test", "check": "on"}
random_line_split
test_form.py
# -*- coding: utf-8 -*- from io import BytesIO import pytest from phi.request.form import FormRequest class TestFormRequest(object):
@pytest.fixture def form_req(self): fr = FormRequest() fr.charset = "utf-8" return fr @pytest.mark.parametrize("body, content", [ ( "name=test&blah=asdfdasf+&check=on", {"blah": "asdfdasf ", "name": "test", "check": "on"} ), ( ...
identifier_body
PhaseInCakeController.py
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
""" PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to Dio...
identifier_body
PhaseInCakeController.py
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions ...
cake_tth = self.model.cake_tth
conditional_block
PhaseInCakeController.py
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: re...
PhaseInCakeController
identifier_name
PhaseInCakeController.py
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher (clemens.prescher@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clip...
self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted)
random_line_split
discover_field_bucket.tsx
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not u...
paddingTop: 0, paddingBottom: 0, paddingRight: 2, paddingLeft: 2, }} /> </div> </EuiFlexItem> )} </EuiFlexGroup> <EuiSpacer size="s" /> </> ); }
aria-label={removeLabel} data-test-subj={`minus-${field.name}-${bucket.value}`} style={{ minHeight: 'auto', minWidth: 'auto',
random_line_split
queue.rs
use std::cmp::Ordering; use base::command::CommandType; use base::party::Party; use base::runner::BattleFlagsType; #[derive(Debug)] struct PartyCommand { party: bool, commands: Vec<Option<CommandType>>, ready: usize, total: usize, } impl PartyCommand { fn
(members: usize) -> Self { let mut commands = Vec::with_capacity(members); for _ in 0..members { commands.push(None); } PartyCommand { party: false, commands: commands, ready: 0, total: members, } } fn command_count(&self) -> usize { self.commands.len() } fn command_get(&self, index...
new
identifier_name
queue.rs
use std::cmp::Ordering; use base::command::CommandType; use base::party::Party; use base::runner::BattleFlagsType; #[derive(Debug)] struct PartyCommand { party: bool, commands: Vec<Option<CommandType>>, ready: usize, total: usize, } impl PartyCommand { fn new(members: usize) -> Self { let mut commands = Vec:...
else if !self.commands[member].is_some() { change = 1; self.ready += 1; } self.commands[member] = Some(command); change } fn command_add_party(&mut self, command: CommandType) -> usize { let change = self.total - self.ready; if self.party { for i in 1..self.total { self.commands[i] =...
{ // All members are now waiting for their individual commands. change = - (self.total as isize) + 1; self.party = false; for i in 0..self.total { self.commands[i] = None; } self.ready = 1; }
conditional_block
queue.rs
use std::cmp::Ordering; use base::command::CommandType; use base::party::Party; use base::runner::BattleFlagsType; #[derive(Debug)] struct PartyCommand { party: bool, commands: Vec<Option<CommandType>>, ready: usize, total: usize, } impl PartyCommand { fn new(members: usize) -> Self { let mut commands = Vec:...
} BattleQueue { waiting: total, total: total, queue: queue, } } /// Returns true if the queue was populated or is in the process of being consumed. pub fn ready(&self) -> bool { self.waiting == 0 } /// Returns the command for the indicated party member. pub fn command_get(&self, party: usize...
for party in parties { total += party.active_count(); queue.push(PartyCommand::new(party.active_count()));
random_line_split
queue.rs
use std::cmp::Ordering; use base::command::CommandType; use base::party::Party; use base::runner::BattleFlagsType; #[derive(Debug)] struct PartyCommand { party: bool, commands: Vec<Option<CommandType>>, ready: usize, total: usize, } impl PartyCommand { fn new(members: usize) -> Self { let mut commands = Vec:...
/// Adds the given command to the queue for the indicated members of the given party. /// /// This will override any commands already given to this party member. If the given party /// already has an attached command, then all members of that party will be invalidated. /// pub fn command_add(&mut self, command:...
{ self.queue[party].command_get(member) }
identifier_body
lib.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/. */ // For simd (currently x86_64/aarch64) #![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "wi...
// Private painting modules mod paint_context; #[deny(unsafe_code)] pub mod display_list; // Fonts #[macro_use] pub mod font; pub mod font_cache_thread; pub mod font_context; pub mod font_template; pub mod paint_thread; // Platform-specific implementations. #[allow(unsafe_code)] mod platform; // Text pub mod text;
random_line_split
affine_linear_operator.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
from __future__ import division from __future__ import print_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.contrib.distributions.python.ops.bijectors.affine_linear_operator_impl import * # pylint: enable=wildcard-import from tensorflow.python.util.all_util import remove_undocumente...
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
/// `UNSPECIFIED_FSP` is the unspecified fractional seconds part. pub const UNSPECIFIED_FSP: i8 = -1; /// `MAX_FSP` is the maximum digit of fractional seconds part. pub const MAX_FSP: i8 = 6; /// `MIN_FSP` is the minimum digit of fractional seconds part. pub const MIN_FSP: i8 = 0; /// `DEFAULT_FSP` is the default digit...
use super::Result;
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; /// `UNSPECIFIED_FSP` is the unspecified fractional seconds part. pub const UNSPECIFIED_FSP: i8 = -1; /// `MAX_FSP` is the maximum digit of fractional seconds part. pub const MAX_FSP: i8 = 6; /// `MIN_FSP` is the minimum digit of fr...
(fsp: i8) -> Result<u8> { if fsp == UNSPECIFIED_FSP { return Ok(DEFAULT_FSP as u8); } if !(MIN_FSP..=MAX_FSP).contains(&fsp) { return Err(invalid_type!("Invalid fsp {}", fsp)); } Ok(fsp as u8) } pub mod binary_literal; pub mod charset; pub mod decimal; pub mod duration; pub mod enum...
check_fsp
identifier_name
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; /// `UNSPECIFIED_FSP` is the unspecified fractional seconds part. pub const UNSPECIFIED_FSP: i8 = -1; /// `MAX_FSP` is the maximum digit of fractional seconds part. pub const MAX_FSP: i8 = 6; /// `MIN_FSP` is the minimum digit of fr...
pub mod binary_literal; pub mod charset; pub mod decimal; pub mod duration; pub mod enums; pub mod json; pub mod set; pub mod time; pub use self::decimal::{dec_encoded_len, Decimal, DecimalDecoder, DecimalEncoder, Res, RoundMode}; pub use self::duration::{Duration, DurationDecoder, DurationEncoder}; pub use self::en...
{ if fsp == UNSPECIFIED_FSP { return Ok(DEFAULT_FSP as u8); } if !(MIN_FSP..=MAX_FSP).contains(&fsp) { return Err(invalid_type!("Invalid fsp {}", fsp)); } Ok(fsp as u8) }
identifier_body
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; /// `UNSPECIFIED_FSP` is the unspecified fractional seconds part. pub const UNSPECIFIED_FSP: i8 = -1; /// `MAX_FSP` is the maximum digit of fractional seconds part. pub const MAX_FSP: i8 = 6; /// `MIN_FSP` is the minimum digit of fr...
Ok(fsp as u8) } pub mod binary_literal; pub mod charset; pub mod decimal; pub mod duration; pub mod enums; pub mod json; pub mod set; pub mod time; pub use self::decimal::{dec_encoded_len, Decimal, DecimalDecoder, DecimalEncoder, Res, RoundMode}; pub use self::duration::{Duration, DurationDecoder, DurationEncode...
{ return Err(invalid_type!("Invalid fsp {}", fsp)); }
conditional_block
maybe_uninit_nodrop.rs
use super::nodrop::NoDrop; use array::Array; use std::mem; use std::ops::{Deref, DerefMut}; /// A combination of NoDrop and “maybe uninitialized”; /// this wraps a value that can be wholly or partially uninitialized. /// /// NOTE: This is known to not be a good solution, but it's the one we have kept /// working on st...
NoDrop<T>); // why don't we use ManuallyDrop here: It doesn't inhibit // enum layout optimizations that depend on T, and we support older Rust. impl<T> MaybeUninit<T> { /// Create a new MaybeUninit with uninitialized interior pub unsafe fn uninitialized() -> Self { MaybeUninit(NoDrop::new(mem::uninitia...
eUninit<T>(
identifier_name
maybe_uninit_nodrop.rs
use super::nodrop::NoDrop; use array::Array; use std::mem; use std::ops::{Deref, DerefMut}; /// A combination of NoDrop and “maybe uninitialized”; /// this wraps a value that can be wholly or partially uninitialized. /// /// NOTE: This is known to not be a good solution, but it's the one we have kept /// working on st...
impl<A: Array> Deref for MaybeUninit<A> { type Target = A; #[inline(always)] fn deref(&self) -> &A { &self.0 } } impl<A: Array> DerefMut for MaybeUninit<A> { #[inline(always)] fn deref_mut(&mut self) -> &mut A { &mut self.0 } }
MaybeUninit(NoDrop::new(mem::uninitialized())) } }
identifier_body
maybe_uninit_nodrop.rs
use super::nodrop::NoDrop; use array::Array; use std::mem; use std::ops::{Deref, DerefMut}; /// A combination of NoDrop and “maybe uninitialized”; /// this wraps a value that can be wholly or partially uninitialized. /// /// NOTE: This is known to not be a good solution, but it's the one we have kept /// working on st...
&self.0 } } impl<A: Array> DerefMut for MaybeUninit<A> { #[inline(always)] fn deref_mut(&mut self) -> &mut A { &mut self.0 } }
random_line_split
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * 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 ap...
inheritedWritableProperties( [], {} ); // $ExpectError inheritedWritableProperties( [], ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an incorrect number of arguments... { inheritedWritableProperties(); // $ExpectError inheritedWritableProperties( [], 2...
inheritedWritableProperties( [], true ); // $ExpectError inheritedWritableProperties( [], [] ); // $ExpectError
random_line_split
wysiwyg.d.ts
import { ResolvedPos } from 'prosemirror-model'; import { Selection } from 'prosemirror-state'; export type WwNodeType = | 'text'
| 'bulletList' | 'orderedList' | 'listItem' | 'table' | 'tableHead' | 'tableBody' | 'tableRow' | 'tableHeadCell' | 'tableBodyCell' | 'blockQuote' | 'thematicBreak' | 'image' | 'hardBreak' | 'lineBreak' | 'customBlock' | 'frontMatter' | 'widget' | 'html'; export type WwMarkType = 'st...
| 'paragraph' | 'heading' | 'codeBlock'
random_line_split
limit.defaults.js
var OdysseusLimiter = require('../index'); var express = require('express'); var request = require('supertest'); describe('limit', function(){ var app; beforeEach(function(){
it('key should be general', (done) => { app.use(OdysseusLimiter.limit({ amount: 2, ttl: 100 })); app.get('/', function(req, res, next){ res.status(200).json({status: 'ok'}); }); request(app) ...
app = express(); }); describe('defaults', function(){
random_line_split
fat-ptr-cast.rs
// Copyright 2015 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait Trait {} // ...
random_line_split
fat-ptr-cast.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let a: &[i32] = &[1, 2, 3]; let b: Box<[i32]> = Box::new([1, 2, 3]); let p = a as *const [i32]; let q = a.as_ptr(); a as usize; //~ ERROR casting b as usize; //~ ERROR non-scalar cast p as usize; //~^ ERROR casting //~^^ HELP cast through a raw pointer // #22955 q as *...
main
identifier_name
fat-ptr-cast.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let a: &[i32] = &[1, 2, 3]; let b: Box<[i32]> = Box::new([1, 2, 3]); let p = a as *const [i32]; let q = a.as_ptr(); a as usize; //~ ERROR casting b as usize; //~ ERROR non-scalar cast p as usize; //~^ ERROR casting //~^^ HELP cast through a raw pointer // #22955 q as *con...
identifier_body
mgmtsystem_action.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it und...
('prevention', 'Preventive Action'), ('improvement', 'Improvement Opportunity') ], 'Response Type') system_id = fields.Many2one('mgmtsystem.system', 'System') company_id = fields.Many2one('res.company', 'Co...
('correction', 'Corrective Action'),
random_line_split
mgmtsystem_action.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it und...
(self, vals): vals.update({ 'reference': self.env['ir.sequence'].get('mgmtsystem.action') }) return super(mgmtsystem_action, self).create(vals) @api.multi def message_auto_subscribe(self, updated_fields, values=None): """Automatically add the responsible user to the ...
create
identifier_name
mgmtsystem_action.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it und...
base = super(mgmtsystem_action, self) return base.message_auto_subscribe(updated_fields, values=values) @api.multi def case_open(self): """ Opens case """ for case in self: values = {'active': True} stages = self.env['mgmtsystem.action.stage'] ...
self.message_subscribe_users(user_ids=[o.user_id.id], subtype_ids=None)
conditional_block
mgmtsystem_action.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it und...
@api.model def create(self, vals): vals.update({ 'reference': self.env['ir.sequence'].get('mgmtsystem.action') }) return super(mgmtsystem_action, self).create(vals) @api.multi def message_auto_subscribe(self, updated_fields, values=None): """Automatically a...
return self.env['mgmtsystem.action.stage'].search([ ('is_starting', '=', True) ]).id
identifier_body
warp_event.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib import script import random rand = random.randint def warp_uptown_east(pc): result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン elif result == 2: ...
rand(12, 14), rand(14, 16)) #ギルド元宮ロビー5F def warp_10000700(pc): script.effect(pc, 4023) script.wait(pc, 1000) script.warp(pc, 20015000, 9, 36) #アイシー島への地下通路 def warp_10000817(pc): result = script.select(pc, ("中立の島", "海賊の島", "聖女の島", "やっぱやめた"), "どこにする?") if result == 1: script.warp(pc, 10054100, 224, 86) #フシギ団の砦(...
and(12, 14), rand(14, 16)) #ギルド元宮ロビー4F elif result == 5: script.warp(pc, 30114000,
conditional_block
warp_event.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib import script import random rand = random.randint def warp_uptown_east(pc): result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン elif result == 2: ...
10054000, 72, 140) #フシギ団の砦 def warp_10001723(pc): script.say(pc, "".join( "上にあるクジラの口まで$R;", "ロープが伸びている…$R;", "$R伝って登れば、$R;", "クジラの口の中に入れそうだ。$R;" ), "warp") result = script.select(pc, ("登らない", "登ってみる"), "登る?") if result == 2: script.warp(pc, 21190000, 32, 184) #口内淵 ID = { 10000003: warp_uptown_east, #ア...
112000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー3F elif result == 4: script.warp(pc, 30113000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー4F elif result == 5: script.warp(pc, 30114000, rand(12, 14), rand(14, 16)) #ギルド元宮ロビー5F def warp_10000700(pc): script.effect(pc, 4023) script.wait(pc, 1000) script.warp(pc, 20015000,...
identifier_body
warp_event.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib import script import random rand = random.randint def warp_uptown_east(pc): result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン elif result == 2: ...
#フシギ団の砦 def warp_10001723(pc): script.say(pc, "".join( "上にあるクジラの口まで$R;", "ロープが伸びている…$R;", "$R伝って登れば、$R;", "クジラの口の中に入れそうだ。$R;" ), "warp") result = script.select(pc, ("登らない", "登ってみる"), "登る?") if result == 2: script.warp(pc, 21190000, 32, 184) #口内淵 ID = { 10000003: warp_uptown_east, #アップタウン東可動橋 10000013...
000, 72, 140)
identifier_name
warp_event.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib import script import random rand = random.randint def warp_uptown_east(pc): result = script.select(pc, ("enter", "north", "south", "west", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(217, 218), rand(126, 129)) #アップタウン elif result == 2: ...
def warp_uptown_west(pc): result = script.select(pc, ("enter", "north", "east", "south", "cancel"), "warp") if result == 1: script.warp(pc, 10023000, rand(37, 38), rand(126, 129)) #アップタウン elif result == 2: script.warp(pc, 10023400, rand(126, 129), rand(29, 32)) #アップタウン北可動橋 elif result == 3: script.warp(pc, 10...
random_line_split
index.d.ts
// Type definitions for @feathersjs/authentication-client 1.0 // Project: http://feathersjs.com/ // Definitions by: Abraao Alves <https://github.com/AbraaoAlves>, Jan Lohage <https://github.com/j2L4e> // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.3 import * as self...
jwtStrategy: string; path: string; entity: string; service: string; timeout: number; }; export interface Passport { setupSocketListeners(): void; connected(): Promise<any>; authenticate(credentials?: FeathersAuthCredentials): any; authenticateSocket(credentials: FeathersAuthCrede...
cookie: string; storageKey: string;
random_line_split
pino-tests.ts
import pino = require("pino"); import { IncomingMessage, ServerResponse } from "http"; import { Socket } from "net"; const log = pino(); const info = log.info; const error = log.error; info("hello world"); error("this is at error level"); info("the answer is %d", 42); info({ obj: 42 }, "hello world"); info({ obj: 42,...
, }; pino().child({ serializers: customSerializers }).info({ test: "should not show up" }); const child2 = log.child({ father: true }); const childChild = child2.child({ baby: true }); log.level = "info"; if (log.levelVal === 30) { console.log("logger level is `info`"); } log.level = "myLevel"; log.myLevel("a mes...
{ return "this is my serializer"; }
identifier_body
pino-tests.ts
import pino = require("pino"); import { IncomingMessage, ServerResponse } from "http"; import { Socket } from "net"; const log = pino(); const info = log.info; const error = log.error; info("hello world"); error("this is at error level"); info("the answer is %d", 42); info({ obj: 42 }, "hello world"); info({ obj: 42,...
msg: "logged with redacted properties", path: "Not shown", }); const anotherRedacted = pino({ redact: { paths: ["anotherPath"], censor: "Not the log you\re looking for", }, }); anotherRedacted.info({ msg: "another logged with redacted properties", anotherPath: "Not shown", }); ...
const redacted = pino({ redact: ["path"], }); redacted.info({
random_line_split
pino-tests.ts
import pino = require("pino"); import { IncomingMessage, ServerResponse } from "http"; import { Socket } from "net"; const log = pino(); const info = log.info; const error = log.error; info("hello world"); error("this is at error level"); info("the answer is %d", 42); info({ obj: 42 }, "hello world"); info({ obj: 42,...
() { return "this is my serializer"; }, }; pino().child({ serializers: customSerializers }).info({ test: "should not show up" }); const child2 = log.child({ father: true }); const childChild = child2.child({ baby: true }); log.level = "info"; if (log.levelVal === 30) { console.log("logger level is `inf...
test
identifier_name
auth.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import datetime from frappe import _ import frappe import frappe.database import frappe.utils from frappe.utils import cint, flt, get_datetime, datetime, date_diff, today import ...
class CookieManager: def __init__(self): self.cookies = {} self.to_delete = [] def init_cookies(self): if not frappe.local.session.get('sid'): return # sid expires in 3 days expires = datetime.datetime.now() + datetime.timedelta(days=3) if frappe.session.sid: self.set_cookie("sid", frappe.session.s...
clear_cookies()
identifier_body
auth.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import datetime from frappe import _ import frappe import frappe.database import frappe.utils from frappe.utils import cint, flt, get_datetime, datetime, date_diff, today import ...
: def __init__(self): # Get Environment variables self.domain = frappe.request.host if self.domain and self.domain.startswith('www.'): self.domain = self.domain[4:] if frappe.get_request_header('X-Forwarded-For'): frappe.local.request_ip = (frappe.get_request_header('X-Forwarded-For').split(",")[0]).str...
HTTPRequest
identifier_name
auth.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import datetime from frappe import _ import frappe import frappe.database import frappe.utils from frappe.utils import cint, flt, get_datetime, datetime, date_diff, today import ...
def check_if_enabled(self, user): """raise exception if user not enabled""" doc = frappe.get_doc("System Settings") if cint(doc.allow_consecutive_login_attempts) > 0: check_consecutive_login_attempts(user, doc) if user=='Administrator': return if not cint(frappe.db.get_value('User', user, 'enabled')): ...
last_password_reset_date = frappe.db.get_value("User", self.user, "last_password_reset_date") or today() last_pwd_reset_days = date_diff(today(), last_password_reset_date) if last_pwd_reset_days > reset_pwd_after_days: return True
conditional_block
auth.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import datetime from frappe import _ import frappe import frappe.database import frappe.utils from frappe.utils import cint, flt, get_datetime, datetime, date_diff, today import ...
except frappe.AuthenticationError: self.update_invalid_login(user) self.fail('Incorrect password', user=user) def fail(self, message, user=None): if not user: user = _('Unknown User') frappe.local.response['message'] = message add_authentication_log(message, user, status="Failed") frappe.db.commit(...
random_line_split
3D.py
""" 3D.py is the interface for plotting Skeleton Wireframes in a 3D perspective using matplotlib """ # 3D Plotting tool from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D # PyKinect XEF modules import Colour #: 3D View Obj class View: def __ini...
(): plt.show() def draw_body(self, body, frame): """ Draws one body at frame """ bone = 0 for joint in self.bodies[body]: for start, end in joint.bones_3D(frame): self.draw_bone(body, start, end, bone) bone += 1 def draw_bone(self, bo...
display
identifier_name
3D.py
""" 3D.py is the interface for plotting Skeleton Wireframes in a 3D perspective using matplotlib """ # 3D Plotting tool from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D # PyKinect XEF modules import Colour #: 3D View Obj class View: def __ini...
return @staticmethod def display(): plt.show() def draw_body(self, body, frame): """ Draws one body at frame """ bone = 0 for joint in self.bodies[body]: for start, end in joint.bones_3D(frame): self.draw_bone(body, start, end, bone) ...
self.display()
conditional_block
3D.py
""" 3D.py is the interface for plotting Skeleton Wireframes in a 3D perspective using matplotlib """ # 3D Plotting tool from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D # PyKinect XEF modules import Colour #: 3D View Obj class View: def __ini...
def draw_body(self, body, frame): """ Draws one body at frame """ bone = 0 for joint in self.bodies[body]: for start, end in joint.bones_3D(frame): self.draw_bone(body, start, end, bone) bone += 1 def draw_bone(self, body, a, b, i): ...
plt.show()
identifier_body
3D.py
""" 3D.py is the interface for plotting Skeleton Wireframes in a 3D perspective using matplotlib """ # 3D Plotting tool from matplotlib import pyplot as plt from matplotlib import animation from mpl_toolkits.mplot3d import Axes3D # PyKinect XEF modules import Colour #: 3D View Obj class View: def __ini...
plt.show() def draw_body(self, body, frame): """ Draws one body at frame """ bone = 0 for joint in self.bodies[body]: for start, end in joint.bones_3D(frame): self.draw_bone(body, start, end, bone) bone += 1 def draw_bone(self, body, ...
def display():
random_line_split
StackPrimitive.tsx
import React, { forwardRef, ReactNode } from 'react'; import classnames from 'classnames'; import styles from './StackPrimitive.module.scss'; export const justifyOptions = { start: 'justify-start', end: 'justify-end', center: 'justify-center', spaceBetween: 'justify-space-between', spaceAround: 'justify-space-aro...
() { if (padding && typeof padding === 'object') { if ('top' in padding) { return [ styles[`padding-top-${padding.top}`], styles[`padding-right-${padding.right}`], styles[`padding-bottom-${padding.bottom}`], styles[`padding-left-${padding.left}`], ]; } return [ styles[`paddin...
getPadding
identifier_name
StackPrimitive.tsx
import React, { forwardRef, ReactNode } from 'react'; import classnames from 'classnames'; import styles from './StackPrimitive.module.scss'; export const justifyOptions = { start: 'justify-start', end: 'justify-end', center: 'justify-center', spaceBetween: 'justify-space-between', spaceAround: 'justify-space-aro...
styles[`margin-top-${margin}`], styles[`margin-right-${margin}`], styles[`margin-bottom-${margin}`], styles[`margin-left-${margin}`], ]; } return []; } function getAlignContent() { if ('alignContent' in props) { return alignContent ? styles[alignContentOptions[alignContent]] : ''; } ...
]; } if (margin && typeof margin !== 'object') { return [
random_line_split
StackPrimitive.tsx
import React, { forwardRef, ReactNode } from 'react'; import classnames from 'classnames'; import styles from './StackPrimitive.module.scss'; export const justifyOptions = { start: 'justify-start', end: 'justify-end', center: 'justify-center', spaceBetween: 'justify-space-between', spaceAround: 'justify-space-aro...
function getMargin() { if (margin && typeof margin === 'object') { if ('top' in margin) { return [ styles[`margin-top-${margin.top}`], styles[`margin-right-${margin.right}`], styles[`margin-bottom-${margin.bottom}`], styles[`margin-left-${margin.left}`], ]; } return [ styl...
{ if (padding && typeof padding === 'object') { if ('top' in padding) { return [ styles[`padding-top-${padding.top}`], styles[`padding-right-${padding.right}`], styles[`padding-bottom-${padding.bottom}`], styles[`padding-left-${padding.left}`], ]; } return [ styles[`padding-t...
identifier_body
StackPrimitive.tsx
import React, { forwardRef, ReactNode } from 'react'; import classnames from 'classnames'; import styles from './StackPrimitive.module.scss'; export const justifyOptions = { start: 'justify-start', end: 'justify-end', center: 'justify-center', spaceBetween: 'justify-space-between', spaceAround: 'justify-space-aro...
return [ styles[`margin-top-${margin.y}`], styles[`margin-right-${margin.x}`], styles[`margin-bottom-${margin.y}`], styles[`margin-left-${margin.x}`], ]; } if (margin && typeof margin !== 'object') { return [ styles[`margin-top-${margin}`], styles[`margin-right-${margin}`], s...
{ return [ styles[`margin-top-${margin.top}`], styles[`margin-right-${margin.right}`], styles[`margin-bottom-${margin.bottom}`], styles[`margin-left-${margin.left}`], ]; }
conditional_block
charge.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import { COSTS, PurchaseInfo } from "smc-webapp/site-licenses/purchase/util"; import { StripeClient } from "../../stripe/client"; import { describe_quota } from "smc-util/db-sc...
stripe: StripeClient, purchase: Purchase, metadata ): Promise<void> { if (purchase.type == "subscription") { stripe.conn.subscriptions.update(purchase.id, { metadata }); } else if (purchase.type == "invoice") { stripe.conn.invoices.update(purchase.id, { metadata }); } }
_purchase_metadata(
identifier_name
charge.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import { COSTS, PurchaseInfo } from "smc-webapp/site-licenses/purchase/util"; import { StripeClient } from "../../stripe/client"; import { describe_quota } from "smc-util/db-sc...
} if (price == null) { dbg("stripe_purchase_product: still missing -- give up"); throw Error( `price for subscription purchase missing -- product_id="${product_id}", subscription="${subscription}"` ); } } // TODO: will need to improve to handle case of *multiple* items on one su...
price = x?.id; break; }
conditional_block
charge.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import { COSTS, PurchaseInfo } from "smc-webapp/site-licenses/purchase/util"; import { StripeClient } from "../../stripe/client"; import { describe_quota } from "smc-util/db-sc...
}); await stripe.conn.prices.create({ currency: "usd", unit_amount: Math.round( COSTS.online_discount * info.cost.cost_sub_year * 100 ), product, recurring: { interval: "year" }, }); } } async function stripe_get_product( stripe: StripeClient, info: PurchaseInfo ...
unit_amount: Math.round( COSTS.online_discount * info.cost.cost_sub_month * 100 ), product, recurring: { interval: "month" },
random_line_split
charge.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import { COSTS, PurchaseInfo } from "smc-webapp/site-licenses/purchase/util"; import { StripeClient } from "../../stripe/client"; import { describe_quota } from "smc-util/db-sc...
unction get_days(info): number { if (info.start == null || info.end == null) throw Error("bug"); return Math.round( (info.end.valueOf() - info.start.valueOf()) / (24 * 60 * 60 * 1000) ); } // When we change pricing, the products in stripe will already // exist with old prices (often grandfathered) so we may ...
dbg("getting product_id"); const product_id = await stripe_get_product(stripe, info); dbg("got product_id", product_id); if (info.subscription == "no") { return await stripe_purchase_product(stripe, product_id, info, dbg); } else { return await stripe_create_subscription(stripe, product_id, info, dbg);...
identifier_body
repology.py
# MIT licensed # Copyright (c) 2019 lilydjwg <lilydjwg@gmail.com>, et al. from nvchecker.api import GetVersionError API_URL = 'https://repology.org/api/v1/project/{}' async def
(name, conf, *, cache, **kwargs): project = conf.get('repology') or name repo = conf.get('repo') subrepo = conf.get('subrepo') if not repo: raise GetVersionError('repo field is required for repology source') url = API_URL.format(project) data = await cache.get_json(url) pkgs = [pkg for pkg in data i...
get_version
identifier_name
repology.py
# MIT licensed # Copyright (c) 2019 lilydjwg <lilydjwg@gmail.com>, et al. from nvchecker.api import GetVersionError API_URL = 'https://repology.org/api/v1/project/{}' async def get_version(name, conf, *, cache, **kwargs): project = conf.get('repology') or name repo = conf.get('repo') subrepo = conf.get('subrep...
pkgs = [pkg for pkg in pkgs if pkg.get('subrepo') == subrepo] if not pkgs: raise GetVersionError('package is not found in subrepo', repo=repo, subrepo=subrepo) versions = [pkg['version'] for pkg in pkgs] return versions
random_line_split
repology.py
# MIT licensed # Copyright (c) 2019 lilydjwg <lilydjwg@gmail.com>, et al. from nvchecker.api import GetVersionError API_URL = 'https://repology.org/api/v1/project/{}' async def get_version(name, conf, *, cache, **kwargs): project = conf.get('repology') or name repo = conf.get('repo') subrepo = conf.get('subrep...
versions = [pkg['version'] for pkg in pkgs] return versions
pkgs = [pkg for pkg in pkgs if pkg.get('subrepo') == subrepo] if not pkgs: raise GetVersionError('package is not found in subrepo', repo=repo, subrepo=subrepo)
conditional_block
repology.py
# MIT licensed # Copyright (c) 2019 lilydjwg <lilydjwg@gmail.com>, et al. from nvchecker.api import GetVersionError API_URL = 'https://repology.org/api/v1/project/{}' async def get_version(name, conf, *, cache, **kwargs):
project = conf.get('repology') or name repo = conf.get('repo') subrepo = conf.get('subrepo') if not repo: raise GetVersionError('repo field is required for repology source') url = API_URL.format(project) data = await cache.get_json(url) pkgs = [pkg for pkg in data if pkg['repo'] == repo] if not pkgs...
identifier_body
cwr.py
# -*- encoding: utf-8 -*- import StringIO import xlsxwriter """ Web app module. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' def generate_cwr_report_excel(cwr): output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) _gen...
def _generate_cwr_report_excel_general(workbook, cwr): results_sheet = workbook.add_worksheet('General info') bold = workbook.add_format({'bold': 1}) header = cwr.transmission.header trailer = cwr.transmission.trailer row = 1 col = 0 results_sheet.write(row, col, 'Sender ID', bold) ...
esults_sheet.write(row, col + 1, record.record_type) row += 1
conditional_block
cwr.py
# -*- encoding: utf-8 -*- import StringIO import xlsxwriter """ Web app module. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' def generate_cwr_report_excel(cwr): output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) _gen...
results_sheet.write(row, col, 'Sender ID', bold) results_sheet.write(row, col + 1, header.sender_id) row += 1 results_sheet.write(row, col, 'Sender Name', bold) results_sheet.write(row, col + 1, header.sender_name) row += 1 results_sheet.write(row, col, 'Sender Type', bold) results_...
header = cwr.transmission.header trailer = cwr.transmission.trailer row = 1 col = 0
random_line_split
cwr.py
# -*- encoding: utf-8 -*- import StringIO import xlsxwriter """ Web app module. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' def generate_cwr_report_excel(cwr): output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) _gen...
workbook, cwr): results_sheet = workbook.add_worksheet('General info') bold = workbook.add_format({'bold': 1}) header = cwr.transmission.header trailer = cwr.transmission.trailer row = 1 col = 0 results_sheet.write(row, col, 'Sender ID', bold) results_sheet.write(row, col + 1, header...
generate_cwr_report_excel_general(
identifier_name
cwr.py
# -*- encoding: utf-8 -*- import StringIO import xlsxwriter """ Web app module. """ __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' def generate_cwr_report_excel(cwr): output = StringIO.StringIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) _gen...
esults_sheet = workbook.add_worksheet('General info') bold = workbook.add_format({'bold': 1}) header = cwr.transmission.header trailer = cwr.transmission.trailer row = 1 col = 0 results_sheet.write(row, col, 'Sender ID', bold) results_sheet.write(row, col + 1, header.sender_id) row ...
identifier_body
utils.rs
// Copyright 2018 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
#[cfg(all(target_os="ios", not(test)))] pub fn d(message: &str) { eprintln!("{}", message); } #[cfg(all(target_os="android", not(test)))] pub fn d(message: &str) { let message = CString::new(message).unwrap(); let message = message.as_ptr(); let tag = CString::new(...
{}
identifier_body
utils.rs
// Copyright 2018 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
(message: &str) { eprintln!("{}", message); } #[cfg(all(target_os="android", not(test)))] pub fn d(message: &str) { let message = CString::new(message).unwrap(); let message = message.as_ptr(); let tag = CString::new("Mentat").unwrap(); let tag = tag.as_ptr(); ...
d
identifier_name
utils.rs
// Copyright 2018 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
/// `error` to a state indicating that no error occurred (`message` is null). /// - If `result` is `Err(e)`, returns a null pointer and stores a string representing the error /// message (which was allocated on the heap and should eventually be freed) into /// `error.message` pub unsafe fn tra...
random_line_split
example2.ts
import { AureliaGridInstance, Column, FieldType, Formatter, Formatters, GridOption, } from '../../aurelia-slickgrid'; interface DataItem { id: number; title: string; duration: string; percentComplete: number; percentComplete2: number; start: Date; finish: Date; effortDriven: boolean; phon...
toggleCompletedProperty(item: any) { // toggle property if (typeof item === 'object') { item.completed = !item.completed; // simulate a backend http call and refresh the grid row after delay setTimeout(() => { this.aureliaGrid.gridService.updateItemById(item.id, item, { highlightR...
{ this.resizerPaused = !this.resizerPaused; this.aureliaGrid.resizerService.pauseResizer(this.resizerPaused); }
identifier_body
example2.ts
import { AureliaGridInstance, Column, FieldType, Formatter, Formatters, GridOption, } from '../../aurelia-slickgrid'; interface DataItem { id: number; title: string; duration: string; percentComplete: number; percentComplete2: number; start: Date; finish: Date; effortDriven: boolean; phon...
} generatePhoneNumber() { let phone = ''; for (let i = 0; i < 10; i++) { phone += Math.round(Math.random() * 9) + ''; } return phone; } togglePauseResizer() { this.resizerPaused = !this.resizerPaused; this.aureliaGrid.resizerService.pauseResizer(this.resizerPaused); } toggl...
{ const randomYear = 2000 + Math.floor(Math.random() * 10); const randomMonth = Math.floor(Math.random() * 11); const randomDay = Math.floor((Math.random() * 29)); const randomPercent = Math.round(Math.random() * 100); this.dataset[i] = { id: i, title: 'Task ' + i, ...
conditional_block
example2.ts
import { AureliaGridInstance, Column, FieldType, Formatter, Formatters, GridOption, } from '../../aurelia-slickgrid'; interface DataItem { id: number; title: string; duration: string; percentComplete: number; percentComplete2: number; start: Date; finish: Date; effortDriven: boolean; phon...
() { // mock a dataset this.dataset = []; for (let i = 0; i < 500; i++) { const randomYear = 2000 + Math.floor(Math.random() * 10); const randomMonth = Math.floor(Math.random() * 11); const randomDay = Math.floor((Math.random() * 29)); const randomPercent = Math.round(Math.random() *...
getData
identifier_name
example2.ts
import { AureliaGridInstance, Column, FieldType, Formatter, Formatters, GridOption, } from '../../aurelia-slickgrid'; interface DataItem { id: number; title: string; duration: string; percentComplete: number; percentComplete2: number; start: Date; finish: Date; effortDriven: boolean; phon...
}, 250); } } }
random_line_split
rst2html.py
#! /usr/bin/env python # Originally by Dave Goodger, from the docutils, distribution. # # Modified for Bazaar to accommodate options containing dots # # This file is in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL,...
description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. ' + default_description) # workaround for bug with <xxx id="tags" name="tags"> in IE from docutils.writers import html4css1 class IESafeHtmlTranslator(html4css1.HTMLTranslator): def starttag(self, node, t...
from docutils.parsers.rst.states import Body # we have some option names that contain dot; which is not allowed by # python-docutils 0.4-4 -- so monkeypatch in a better pattern # # This is a bit gross to patch because all this is built up at load time. Body.pats['optname'] = r'[a-zA-Z0-9][a-zA-Z0-9....
conditional_block
rst2html.py
#! /usr/bin/env python # Originally by Dave Goodger, from the docutils, distribution. # # Modified for Bazaar to accommodate options containing dots # # This file is in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL,...
mywriter = html4css1.Writer() mywriter.translator_class = IESafeHtmlTranslator publish_cmdline(writer=mywriter, description=description)
def starttag(self, node, tagname, suffix='\n', empty=0, **attributes): x = html4css1.HTMLTranslator.starttag(self, node, tagname, suffix, empty, **attributes) y = x.replace('id="tags"', 'id="tags_"') y = y.replace('name="tags"', 'name="tags_"') ...
identifier_body
rst2html.py
#! /usr/bin/env python # Originally by Dave Goodger, from the docutils, distribution. # # Modified for Bazaar to accommodate options containing dots # # This file is in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL,...
(self, node, tagname, suffix='\n', empty=0, **attributes): x = html4css1.HTMLTranslator.starttag(self, node, tagname, suffix, empty, **attributes) y = x.replace('id="tags"', 'id="tags_"') y = y.replace('name="tags"', 'name="tags_"') y = y.rep...
starttag
identifier_name
rst2html.py
#! /usr/bin/env python # Originally by Dave Goodger, from the docutils, distribution. # # Modified for Bazaar to accommodate options containing dots # # This file is in the public domain. """ A minimal front end to the Docutils Publisher, producing HTML. """ try: import locale locale.setlocale(locale.LC_ALL,...
y = y.replace('name="tags"', 'name="tags_"') y = y.replace('href="#tags"', 'href="#tags_"') return y mywriter = html4css1.Writer() mywriter.translator_class = IESafeHtmlTranslator publish_cmdline(writer=mywriter, description=description)
empty, **attributes) y = x.replace('id="tags"', 'id="tags_"')
random_line_split
p2p_disconnect_ban.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node disconnect and ban behavior""" import time from test_framework.test_framework import GuldenT...
DisconnectBanTest().main()
conditional_block
p2p_disconnect_ban.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node disconnect and ban behavior""" import time from test_framework.test_framework import GuldenT...
self.log.info("setban: successfully ban single IP address") assert_equal(len(self.nodes[1].getpeerinfo()), 2) # node1 should have 2 connections to node0 at this point self.nodes[1].setban(subnet="127.0.0.1", command="add") wait_until(lambda: len(self.nodes[1].getpeerinfo()) == 0, timeo...
def set_test_params(self): self.num_nodes = 2 def run_test(self): self.log.info("Test setban and listbanned RPCs")
random_line_split
p2p_disconnect_ban.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node disconnect and ban behavior""" import time from test_framework.test_framework import GuldenT...
(self): self.num_nodes = 2 def run_test(self): self.log.info("Test setban and listbanned RPCs") self.log.info("setban: successfully ban single IP address") assert_equal(len(self.nodes[1].getpeerinfo()), 2) # node1 should have 2 connections to node0 at this point self.nodes...
set_test_params
identifier_name