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
restycheck.js
var openresty = null var Server = 'api.openresty.org'; var savedAnchor = null; var timer = null; $(document).ready(init); var Links = [ ['/=/view/t/a/水煮鱼', {c:'北京',_user:"lifecai.s",t:50}], ['/=/view/Honorlist/limit/500', {_user:'qyliu.Public'}], ['/=/model/Post/~/~', {_offset:0, _count: 10, _user:'agentz...
var html = '<tr class="result">'; for (var i = 0; i < row.length; i++) { html += '<td>' + row[i] + '</td>'; } html += '</tr>\n'; return html; } function toURL (link) { var url = 'http://' + server + link[0] + '?'; var firstTime = true; var params = link[1]; for (var key in pa...
(row) {
identifier_name
restycheck.js
var openresty = null var Server = 'api.openresty.org'; var savedAnchor = null; var timer = null; $(document).ready(init); var Links = [ ['/=/view/t/a/水煮鱼', {c:'北京',_user:"lifecai.s",t:50}], ['/=/view/Honorlist/limit/500', {_user:'qyliu.Public'}], ['/=/model/Post/~/~', {_offset:0, _count: 10, _user:'agentz...
function genCallback (link) { var beginTime = now(); openresty.callback = function (res) { var elapsed = now() - beginTime; renderRes([link[0], link[1]], elapsed, res); }; } function renderRes (link, elapsed, res) { //alert("HERE!"); var row; var account = link[1]._user.replac...
} function now () { return (new Date()).getTime(); }
random_line_split
restycheck.js
var openresty = null var Server = 'api.openresty.org'; var savedAnchor = null; var timer = null; $(document).ready(init); var Links = [ ['/=/view/t/a/水煮鱼', {c:'北京',_user:"lifecai.s",t:50}], ['/=/view/Honorlist/limit/500', {_user:'qyliu.Public'}], ['/=/model/Post/~/~', {_offset:0, _count: 10, _user:'agentz...
toURL (link) { var url = 'http://' + server + link[0] + '?'; var firstTime = true; var params = link[1]; for (var key in params) { if (key == 'callback' || key == '_rand') continue; if (firstTime) { firstTime = false; } else { url += '&'; } ...
html = '<tr class="result">'; for (var i = 0; i < row.length; i++) { html += '<td>' + row[i] + '</td>'; } html += '</tr>\n'; return html; } function
identifier_body
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ "jso...
setup( name='pycorm', version='0.2.13', description="a pico orm that uses jsonschema", long_description=readme + '\n\n' + history, author="Johannes Valbjørn", author_email='johannes.valbjorn@gmail.com', url='https://github.com/sloev/pycorm', packages=[ 'pycorm', ], packag...
]
random_line_split
meetings.js
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function
() { return ( <Layout pageTitle="Meetings" description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event." > <Div maxWidth="1200px" flexd flexWrap="wrap" mt={12} mx="auto" ...
Meetings
identifier_name
meetings.js
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function Meetings() { return ( <Layout pageTitle="Meet...
}
random_line_split
meetings.js
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function Meetings()
<Header type={1} fs={["2xl", "3xl"]} color="grey8"> Next Meetup Event </Header> <P fs="lg" color="grey8" lh="normal"> Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event. </...
{ return ( <Layout pageTitle="Meetings" description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event." > <Div maxWidth="1200px" flexd flexWrap="wrap" mt={12} mx="auto" m...
identifier_body
mod.rs
// Copyright 2015-2017 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 lat...
pub use self::schedule::{Schedule, CleanDustMode}; pub use types::executed::CallType;
pub use self::factory::Factory;
random_line_split
parity_signing.rs
// Copyright 2015-2017 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 lat...
use jsonrpc_core::Error; use futures::BoxFuture; use v1::types::{U256, H160, Bytes, ConfirmationResponse, TransactionRequest, Either}; build_rpc_trait! { /// Signing methods implementation. pub trait ParitySigning { type Metadata; /// Posts sign request asynchronously. /// Will return a confirmation ID for l...
//! ParitySigning rpc interface.
random_line_split
u_char.rs
b' or 'B', 11, etc. Returns /// none if the character does not refer to a digit in the given radix. /// /// # Panics /// /// Panics if given a radix outside the range [0..36]. #[unstable = "pending integer conventions"] fn to_digit(self, radix: uint) -> Option<uint>; /// Returns an iter...
{ derived_property::XID_Continue(self) }
identifier_body
u_char.rs
`false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unstable = "pending integer conventions"] fn is_digit(self, radix: uint) -> bool; /// Converts a character to the corresponding digit. /// /// # Return value /// /// If `c` is between '0' an...
is_alphabetic
identifier_name
u_char.rs
Compared to `is_numeric()`, this function only recognizes the characters /// `0-9`, `a-z` and `A-Z`. /// /// # Return value /// /// Returns `true` if `c` is a valid digit under `radix`, and `false` /// otherwise. /// /// # Panics /// /// Panics if given a radix > 36. #[unsta...
#[stable] fn len_utf8(self) -> uint; /// Returns the amount of bytes this character would need if encoded in /// UTF-16. #[stable] fn len_utf16(self) -> uint; /// Encodes this character as UTF-8 into the provided byte buffer, /// and then returns the number of bytes written. /// ...
/// Returns the amount of bytes this character would need if encoded in /// UTF-8.
random_line_split
lib.rs
#![feature(globs)] use std::collections::HashMap; use std::fmt::{Show, FormatError, Formatter}; use std::os; use std::str; pub use self::gnu::GnuMakefile; // XXX: no idea why this is necessary #[path = "gnu/mod.rs"] pub mod gnu; pub type TokenResult<T> = Result<T, TokenError>; pub type ParseResult<T> = Result<T, Pa...
<'a> { rules: HashMap<&'a [u8], MakefileRule<'a>>, funcs: HashMap<&'a [u8], &'a [u8]> } pub struct MakefileRule<'a> { name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8] } pub struct ParseError { pub message: String, pub code: int } pub struct TokenError { pub message: String, ...
MakefileDag
identifier_name
lib.rs
#![feature(globs)] use std::collections::HashMap; use std::fmt::{Show, FormatError, Formatter}; use std::os; use std::str; pub use self::gnu::GnuMakefile; // XXX: no idea why this is necessary #[path = "gnu/mod.rs"] pub mod gnu; pub type TokenResult<T> = Result<T, TokenError>; pub type ParseResult<T> = Result<T, Pa...
} impl<'a> MakefileRule<'a> { #[inline] pub fn new(name: &'a [u8], deps: Vec<&'a MakefileRule<'a>>, body: &'a [u8]) -> MakefileRule<'a> { MakefileRule { name: name, deps: deps, body: body } } } impl ParseError { #[inline] pub fn new(msg: String, code: int) -> Pars...
}
random_line_split
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to m...
} } } impl Sdl2TtfContext { /// Loads a font from the given file with the given size in points. pub fn load_font<'ttf, P: AsRef<Path>>( &'ttf self, path: P, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font(path, point_size) } ...
unsafe { ttf::TTF_Quit();
random_line_split
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to m...
/// Loads the font at the given index of the file, with the given /// size in points. pub fn load_font_at_index<'ttf, P: AsRef<Path>>( &'ttf self, path: P, index: u32, point_size: u16, ) -> Result<Font<'ttf, 'static>, String> { internal_load_font_at_index(path, ...
{ internal_load_font(path, point_size) }
identifier_body
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to m...
else { Ok(internal_load_font_from_ll(raw, Some(rwops))) } } } /// Returns the version of the dynamically linked `SDL_TTF` library pub fn get_linked_version() -> Version { unsafe { Version::from_ll(*ttf::TTF_Linked_Version()) } } /// An error for when `sdl2_ttf` is attempted initialized tw...
{ Err(get_error()) }
conditional_block
context.rs
use get_error; use rwops::RWops; use std::error; use std::fmt; use std::io; use std::os::raw::{c_int, c_long}; use std::path::Path; use sys::ttf; use version::Version; use super::font::{ internal_load_font, internal_load_font_at_index, internal_load_font_from_ll, Font, }; /// A context manager for `SDL2_TTF` to m...
(&self) -> &str { match *self { InitError::AlreadyInitializedError => "SDL2_TTF has already been initialized", InitError::InitializationError(ref error) => error.description(), } } fn cause(&self) -> Option<&dyn error::Error> { match *self { InitError...
description
identifier_name
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 't...
# 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials...
random_line_split
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 't...
(ProcessError): pass class TimeoutError(ProcessError): pass class AuthenticationError(ProcessError): pass # This is down here because _multiprocessing uses BufferTooShort #import _multiprocessing # # Definitions not depending on native semaphores # def Manager(): ''' Returns a manager associate...
BufferTooShort
identifier_name
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 't...
def Event(): ''' Returns an event object ''' from multiprocessing.synchronize import Event return Event() def Queue(maxsize=0): ''' Returns a queue object ''' from multiprocessing.queues import Queue return Queue(maxsize) def JoinableQueue(maxsize=0): ''' Returns a qu...
''' Returns a bounded semaphore object ''' from multiprocessing.synchronize import BoundedSemaphore return BoundedSemaphore(value)
identifier_body
__init__.py
# # Package analogous to 'threading.py' but using processes # # multiprocessing/__init__.py # # This package is intended to duplicate the functionality (and much of # the API) of threading.py but uses processes instead of threads. A # subpackage 'multiprocessing.dummy' has the same API but is a simple # wrapper for 't...
else: try: num = os.sysconf('SC_NPROCESSORS_ONLN') except (ValueError, OSError, AttributeError): num = 0 if num >= 1: return num else: raise NotImplementedError('cannot determine number of cpus') def freeze_support(): ''' Check whether this ...
comm = '/sbin/sysctl -n hw.ncpu' if sys.platform == 'darwin': comm = '/usr' + comm try: with os.popen(comm) as p: num = int(p.read()) except ValueError: num = 0
conditional_block
test_custom_dm_diam_dm_proj.py
import shesha.config as conf simul_name = "bench_scao_sh_16x16_8pix" layout = "layoutDeFab_SH" # loop
p_loop.set_niter(1000) p_loop.set_ittime(0.002) # =1/500 # geom p_geom = conf.Param_geom() p_geom.set_zenithangle(0.) # tel p_tel = conf.Param_tel() p_tel.set_diam(4.0) p_tel.set_cobs(0.2) # atmos p_atmos = conf.Param_atmos() p_atmos.set_r0(0.16) p_atmos.set_nscreens(1) p_atmos.set_frac([1.0]) p_atmos.set_alt([0...
p_loop = conf.Param_loop()
random_line_split
mpl_msk_spb.py
# -*- coding: utf-8 -*- # http://matplotlib.org/basemap/users/examples.html from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # create new figure, axes instances. fig=plt.figure() ax=fig.add_axes([0.1,0.1,0.8,0.8]) # setup mercator map projection. m = Basemap(llcrnrlon=0.,llcrn...
# draw meridians m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1]) ax.set_title('Great Circle from New York to London') plt.show()
random_line_split
__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # Desarrollado por rNet Soluciones # Jefe de Proyecto: Ing. Ulises Tlatoani Vidal Rieder # Desarrollador: Ing. Salvador Daniel Pelayo Gómez. # Analista: Lic. David Padilla Bobadilla # ###################...
import report_cp
# You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ##############################################################################
random_line_split
sched.rs
use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { ...
/// Add a CPU to CpuSet. /// `field` is the CPU id to add pub fn set(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok...
{ if field >= CpuSet::count() { Err(Errno::EINVAL) } else { Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) }) } }
identifier_body
sched.rs
use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { ...
} /// Remove a CPU from CpuSet. /// `field` is the CPU id to remove pub fn unset(&mut self, field: usize) -> Result<()> { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { unsafe { libc::CPU_CLR(field, &mut self.cpu_set);}...
{ unsafe { libc::CPU_SET(field, &mut self.cpu_set); } Ok(()) }
conditional_block
sched.rs
use std::os::unix::io::RawFd; use crate::unistd::Pid; use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. libc_bitflags! { /// Options for use with [`clone`] pub struct CloneFlags: c_int { ...
{ cpu_set: libc::cpu_set_t, } impl CpuSet { /// Create a new and empty CpuSet. pub fn new() -> CpuSet { CpuSet { cpu_set: unsafe { mem::zeroed() }, } } /// Test to see if a CPU is in the CpuSet. /// `field` is the CPU id ...
CpuSet
identifier_name
teamHandler.js
// Copyright 2015 rain1017. // // 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 wr...
return this.app.controllers.team.quitAsync(teamId, playerId) .nodeify(next); }; proto.push = function(msg, session, next){ var teamId = msg.teamId; if(!teamId){ return next(new Error('teamId is missing')); } return this.app.controllers.team.pushAsync(teamId, msg.playerIds, msg.route, m...
{ return next(new Error('playerId or teamId is missing')); }
conditional_block
teamHandler.js
// Copyright 2015 rain1017. // // 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 wr...
if(!playerId || !teamId){ return next(new Error('playerId or teamId is missing')); } return this.app.controllers.team.joinAsync(teamId, playerId) .nodeify(next); }; proto.quit = function(msg, session, next){ var playerId = session.uid; var teamId = msg.teamId; if(!playerId || !teamI...
var teamId = msg.teamId;
random_line_split
roll-the-dice.py
## # @author Brandon Michael # Roll the dice based on the user's input. Track double rolls and display # the double totals. # import the random library import random # Set the start and end values the same as a dice start = 1 end = 6 # Set the running total for doubles found totalDoubles = 0 # Get the number of tim...
else: print(roll_1, roll_2) # Print the results print(totalDoubles, "double(s) rolled.")
totalDoubles = totalDoubles + 1 print(roll_1, roll_2, "Double !")
conditional_block
roll-the-dice.py
## # @author Brandon Michael # Roll the dice based on the user's input. Track double rolls and display # the double totals. # import the random library import random # Set the start and end values the same as a dice start = 1 end = 6 # Set the running total for doubles found totalDoubles = 0 # Get the number of tim...
totalDoubles = totalDoubles + 1 print(roll_1, roll_2, "Double !") else: print(roll_1, roll_2) # Print the results print(totalDoubles, "double(s) rolled.")
roll_1 = random.randint(start, end) roll_2 = random.randint(start, end) # Check if rolls equal each other, and track the double count if roll_1 == roll_2:
random_line_split
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject'; export class ReduceOperator<T, R> implements Operator<T, R> { acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, ac...
<T, R> extends Subscriber<T> { acc: R; hasSeed: boolean; hasValue: boolean = false; project: (acc: R, x: T) => R; constructor(destination: Subscriber<T>, project: (acc: R, x: T) => R, acc?: R) { super(destination); this.acc = acc; this.project = project; this.hasSeed = typeof acc !== 'undefi...
ReduceSubscriber
identifier_name
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject'; export class ReduceOperator<T, R> implements Operator<T, R> { acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, ac...
_complete() { if (this.hasValue || this.hasSeed) { this.destination.next(this.acc); } this.destination.complete(); } }
{ if (this.hasValue || (this.hasValue = this.hasSeed)) { const result = tryCatch(this.project).call(this, this.acc, x); if (result === errorObject) { this.destination.error(errorObject.e); } else { this.acc = result; } } else { this.acc = x; this.hasValue = tr...
identifier_body
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject'; export class ReduceOperator<T, R> implements Operator<T, R> { acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, ac...
this.destination.complete(); } }
{ this.destination.next(this.acc); }
conditional_block
reduce-support.ts
import Operator from '../Operator'; import Subscriber from '../Subscriber'; import tryCatch from '../util/tryCatch'; import {errorObject} from '../util/errorObject';
acc: R; project: (acc: R, x: T) => R; constructor(project: (acc: R, x: T) => R, acc?: R) { this.acc = acc; this.project = project; } call(subscriber: Subscriber<T>): Subscriber<T> { return new ReduceSubscriber(subscriber, this.project, this.acc); } } export class ReduceSubscriber<T, R> extend...
export class ReduceOperator<T, R> implements Operator<T, R> {
random_line_split
checkbox.type.spec.ts
import { FormlyFieldConfig } from '@ngx-formly/core'; import { createFieldComponent, ɵCustomEvent } from '@ngx-formly/core/testing'; import { FormlyNzCheckboxModule } from '@ngx-formly/ng-zorro-antd/checkbox'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; const renderComponent = (field: ...
}); }); it('should render boolean type', () => { const { query } = renderComponent({ key: 'name', type: 'boolean', }); expect(query('formly-wrapper-nz-form-field')).not.toBeNull(); expect(query('.ant-checkbox-indeterminate')).not.toBeNull(); expect(query('input[type="checkbox"...
random_line_split
SmoothScroll.js
; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = documen...
var deltaX = event.wheelDeltaX || 0; var deltaY = event.wheelDeltaY || 0; // use wheelDelta if deltaX/Y is not available if (!deltaX && !deltaY) { deltaY = event.wheelDelta || 0; } // scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes i...
(isNodeName(target, "embed") && /\.pdf/i.test(target.src))) { return true; }
random_line_split
SmoothScroll.js
var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = document....
// scale by step size // delta is 120 most of the time // synaptics seems to send 1 sometimes if (Math.abs(deltaX) > 1.2) { deltaX *= stepsize / 120; } if (Math.abs(deltaY) > 1.2) { deltaY *= stepsize / 120; } scrollArray(overflowing, -deltaX, -deltaY); event.preventDe...
{ deltaY = event.wheelDelta || 0; }
conditional_block
SmoothScroll.js
'px'; pending = false; }, 500); // act rarely to stay fast } }; html.style.height = ''; setTimeout(refresh, 10); addEvent("DOMNodeInserted", refresh); addEvent("DOMNodeRemoved", refresh); // clearfix if (root.offsetHeight <= windowHeight) { ...
directionCheck
identifier_name
SmoothScroll.js
; var activeElement; var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 }; /** * Sets up scrolls array, determines if frames are involved. */ function init() { if (!document.body) return; var body = document.body; var html = documen...
que.push({ x: left, y: top, lastX: (left < 0) ? 0.99 : -0.99, lastY: (top < 0) ? 0.99 : -0.99, start: +new Date }); // don't act if there's a pending queue if (pending) { return; } var scrollWindow = (elem === document.body); var step = function() { ...
{ delay || (delay = 1000); directionCheck(left, top); if (acceleration) { var now = +new Date; var elapsed = now - lastScroll; if (elapsed < accelDelta) { var factor = (1 + (30 / elapsed)) / 2; if (factor > 1) { factor = Math.min(factor, accelMax); lef...
identifier_body
async-gen-dstr-const-obj-ptrn-id-init-fn-name-cover.js
// This file was procedurally generated from the following sources: // - src/dstr-binding-for-await/obj-ptrn-id-init-fn-name-cover.case // - src/dstr-binding-for-await/default/for-await-of-async-gen-const.template /*--- description: SingleNameBinding assigns `name` to "anonymous" functions "through" cover grammar (for-...
for await ( ForDeclaration of AssignmentExpression ) Statement [...] 2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet, async). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 4. Let destructuring be IsDestructuring of lhs....
flags: [generated, async] info: | IterationStatement :
random_line_split
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed...
/// Convert the `Rawlink` into an Option value pub fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> { if self.p.is_null() { None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub f...
{ unsafe { mem::transmute(self.p.as_ref()) } }
identifier_body
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed...
None } else { Some(unsafe { mem::transmute(self.p) }) } } /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn e...
random_line_split
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed...
() -> Rawlink<T> { Rawlink::none() } }
default
identifier_name
rawlink.rs
// This file is part of Intrusive. // Intrusive is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Intrusive is distributed...
} /// Return the `Rawlink` and replace with `Rawlink::none()` pub fn take(&mut self) -> Rawlink<T> { mem::replace(self, Rawlink::none()) } } impl<T> PartialEq for Rawlink<T> { #[inline] fn eq(&self, other: &Rawlink<T>) -> bool { self.p == other.p } } impl<T> Clone for Raw...
{ Some(unsafe { mem::transmute(self.p) }) }
conditional_block
local-storage.d.ts
import { StorageEngine } from './storage'; /** * @name LocalStorage * @description * The LocalStorage storage engine uses the browser's local storage system for * storing key/value pairs. * * Note: LocalStorage should ONLY be used for temporary data that you can afford to lose. * Given disk space constraints on ...
extends StorageEngine { constructor(options?: {}); /** * Get the value of a key in LocalStorage * @param {string} key the key you want to lookup in LocalStorage */ get(key: string): Promise<string>; /** * Set a key value pair and save it to LocalStorage * @param {string} key th...
LocalStorage
identifier_name
local-storage.d.ts
import { StorageEngine } from './storage'; /** * @name LocalStorage * @description * The LocalStorage storage engine uses the browser's local storage system for * storing key/value pairs. * * Note: LocalStorage should ONLY be used for temporary data that you can afford to lose. * Given disk space constraints on ...
* @param {string} key the key you want to lookup in LocalStorage */ get(key: string): Promise<string>; /** * Set a key value pair and save it to LocalStorage * @param {string} key the key you want to save to LocalStorage * @param {string} value the value of the key you're saving */...
*/ export declare class LocalStorage extends StorageEngine { constructor(options?: {}); /** * Get the value of a key in LocalStorage
random_line_split
util.py
import json import os import jinja2 from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), exten...
(request, output_type=message.FORMAT_JSON): if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '200 OK' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) else: reque...
send_success
identifier_name
util.py
import json import os import jinja2 from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), exten...
def send_success(request, output_type=message.FORMAT_JSON): if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '200 OK' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.response.out.write(json_data) ...
request.response.out.write(_get_jinja_template('not_found.html').render( ))
conditional_block
util.py
from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), extensions=['jinja2.ext.autoescape'], ...
import json import os import jinja2
random_line_split
util.py
import json import os import jinja2 from mlabns.util import message def _get_jinja_environment(): current_dir = os.path.dirname(__file__) templates_dir = os.path.join(current_dir, '../templates') return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir), exten...
def send_not_found(request, output_type=message.FORMAT_HTML): request.error(404) if output_type == message.FORMAT_JSON: data = {} data['status_code'] = '404 Not found' json_data = json.dumps(data) request.response.headers['Content-Type'] = 'application/json' request.re...
request.response.headers['Access-Control-Allow-Origin'] = '*' request.response.headers['Content-Type'] = 'application/json' request.response.set_status(204)
identifier_body
run.py
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'rew...
worksheet.write(row, col,len(results)) workbook.close() print "Done." def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__": main()
date = str(datetime.now().date()) print "Maping" excel_template = xlrd.open_workbook("map.xlsx") copyfile('map.xlsx', "map {}.xlsx".format(date)) excel_data = xlrd.open_workbook("data.xlsx") t1_excel_mapper = create_mapper(wb=excel_template,table_index=1,row_rules=row_rules_sheet1_t1,col_rules=col_rules_sheet...
identifier_body
run.py
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'rew...
(): date = str(datetime.now().date()) print "Maping" excel_template = xlrd.open_workbook("map.xlsx") copyfile('map.xlsx', "map {}.xlsx".format(date)) excel_data = xlrd.open_workbook("data.xlsx") t1_excel_mapper = create_mapper(wb=excel_template,table_index=1,row_rules=row_rules_sheet1_t1,col_rules=col_rules...
main
identifier_name
run.py
from shutil import copyfile from datetime import datetime
row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'reward' in data['type'].lower() or 'reward' in data['type'].lower()} row_rules_sheet1_t2 = row_rules_sheet1_t1 col_rules_sh...
from ExcelMapper.mapper import * import xlrd import xlsxwriter
random_line_split
run.py
from shutil import copyfile from datetime import datetime from ExcelMapper.mapper import * import xlrd import xlsxwriter row_rules_sheet1_t1 = { 'found "risk"': lambda data: 'risk' in data['type'], 'found "Risk"': lambda data: 'Risk' in data['type'], 'found "reward"(ignore letter casing)': lambda data: 'rew...
workbook.close() print "Done." def clone_sheet(to_clone_sheet,new_sheet): for row in range(0,to_clone_sheet.nrows): for col in range(0,to_clone_sheet.ncols): new_sheet.write(row,col,to_clone_sheet.cell_value(row, col)) if __name__ == "__main__": main()
worksheet.write(row, col,len(results))
conditional_block
setup.py
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-tvdb', version='0.1', packages=['tvdb'], include_package_data=True, ...
'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7',
random_line_split
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): ...
def cli_describe(self): (options, args) = self.get_describe_parser() self.group_describe(args) def group_describe(self,groups=None): params = {} if groups: self.euca.connection.build_list_params(params,groups,'GroupNames') try: list = self.euca.connection.get_list('DescribeGr...
parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION") return parser.parse_args()
random_line_split
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): ...
else: return None def endElement(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, value) def get_describe_parser(self): parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION...
return self.group_auths
conditional_block
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): ...
(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, value) def get_describe_parser(self): parser = OptionParser("usage: %prog [GROUPS...]",version="Eucalyptus %prog VERSION") return parser.parse_args() def cli...
endElement
identifier_name
groups.py
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): ...
def cli_delete(self): (options, args) = self.get_single_parser() self.group_delete(args[0]) def group_delete(self, groupName): try: reply = self.euca.connection.get_object('DeleteGroup', {'GroupName':groupName},BooleanResponse) print reply except EC2ResponseError, ex: ...
try: reply = self.euca.connection.get_object('AddGroup', {'GroupName':groupName}, BooleanResponse) print reply except EC2ResponseError, ex: self.euca.handle_error(ex)
identifier_body
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = req...
else { return { "page_type": "good", "aduan_id": aduan_data[1][0] } } } else { return { "page_type": "error" } } // Should not get here .. is bad! return { "page_type": "unknown" } } function ex...
{ return { "page_type": "empty", "aduan_id": aduan_data[1][0] } }
conditional_block
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = req...
(page_parsed) { // console.error("TYPE: " + typeof(page_parsed)) // DEBUG: // console.error("TITLE IS " + pageParsed('head title').text()) // If title is "PublicViewStatus"; is OK; otherwise ERROR out!! if (page_parsed('head title').text() == "PublicViewStatus") { // Aduan Information ...
recognize_page_type
identifier_name
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = req...
) */ const aduan_data = page_parsed('#Table9').parsetable(false, false, true) // DEBUG: /* console.error("SIZE: " + aduan_data.length) aduanData[0].every((element, index, array) => { console.error("EL: " + util.inspect(element) + " ID: " + index ) ...
{ // console.error("TYPE: " + typeof(page_parsed)) // DEBUG: // console.error("TITLE IS " + pageParsed('head title').text()) // If title is "PublicViewStatus"; is OK; otherwise ERROR out!! if (page_parsed('head title').text() == "PublicViewStatus") { // Aduan Information // id="dlAd...
identifier_body
recognize-page-type.js
/** * Created by leow on 2/12/17. */ "use strict"; // Stdlib const util = require("util") // Constants const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!" const FATAL_CONTENT = "Page does not exist!" const FATAL_UNKNOWN = "Unknown Error!" // Libs const cheerio = require('cheerio') const tableParser = req...
} const page_parsed = cheerio.load(loaded_raw_content) // Setup cheerio-tableparser tableParser(page_parsed) // Extract out page type and other goodies? const res = recognize_page_type(page_parsed) if (res.page_type == "error") { // Assumes Error Page; but it is loaded correctly .....
random_line_split
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: c...
() { console.log('kanban:loaded project'); var layerId = this.kanban.columns[0].filters.layerIds[0]; this.layer = this.$layerService.findLayer(layerId); if (this.layer) { if (this.layer.typeUrl && this.$layerService.typesResources.hasOwnProperty(this.laye...
initLayer
identifier_name
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: c...
console.log('feature types'); console.log(this.featureTypes); } } } } }
{ this.featureTypes = this.$layerService.typesResources[this.layer.typeUrl].featureTypes; }
conditional_block
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: c...
private initLayer() { console.log('kanban:loaded project'); var layerId = this.kanban.columns[0].filters.layerIds[0]; this.layer = this.$layerService.findLayer(layerId); if (this.layer) { if (this.layer.typeUrl && this.$layerService.typesResourc...
{ $scope.vm = this; var par = <any>$scope.$parent; this.kanban = par.widget.data; this.$messageBus.subscribe("typesource", (s: string) => { this.initLayer(); }); this.initLayer(); }
identifier_body
KanbanBoardCtrl.ts
module KanbanColumn { export interface IKanbanBoardScope extends ng.IScope { vm: KanbanBoardCtrl; } export class KanbanConfig { featureTypesToAdd: string[]; columns: Column[]; } export class KanbanBoardCtrl { private scope: IKanbanBoardScope; public feeds: c...
} } } } }
console.log(this.featureTypes);
random_line_split
index.ts
import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatCardModule} from '@angular/material/card'; import {MatCheckboxModule} from '@angular/material/checkbox'; import {MatRadioModule} from '@angular/material/radio...
CheckboxReactiveFormsExample, ]; @NgModule({ imports: [ CommonModule, MatCardModule, MatCheckboxModule, MatRadioModule, FormsModule, ReactiveFormsModule, ], declarations: EXAMPLES, exports: EXAMPLES, }) export class CheckboxExamplesModule {}
const EXAMPLES = [ CheckboxConfigurableExample, CheckboxOverviewExample, CheckboxHarnessExample,
random_line_split
index.ts
import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatCardModule} from '@angular/material/card'; import {MatCheckboxModule} from '@angular/material/checkbox'; import {MatRadioModule} from '@angular/material/radio...
{}
CheckboxExamplesModule
identifier_name
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function Store(na...
//event listener function makeStore(event){ event.preventDefault(); myTable.innerHtml = ''; var name = event.target.name.value; var minCust = parseInt(event.target.minCust.value); var maxCust = parseInt(event.target.maxCust.value); var avgCookieSale = parseFloat(event.target.avgCookieSale.value); var add...
{ var footerRef = document.getElementById('tableFooter'); if (footerRef !== null){ footerRef.parentElement.removeChild(footerRef); } }
identifier_body
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function
(name, minCust, maxCust, avgCookieSale) { this.name = name; this.minCust = minCust; this.maxCust = maxCust; this.avgCookieSale = avgCookieSale; this.hourlySales = []; this.hourlyCust = []; this.totalSales = 0; this.calcSalesByHour(); allStores.push(this); }; Store.prototype.calcCustPerHour = function...
Store
identifier_name
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function Store(na...
function makeHeader() { var thEl = document.createElement('th'); var trEl = document.createElement('tr'); thEl.textContent = 'Location'; trEl.appendChild(thEl); for(var i = 0; i < timesOfDay.length; i++){ var thEl = document.createElement('th'); // console.log('hello'); thEl.textContent = timesOf...
trEl.appendChild(tdEl); myTable.appendChild(trEl); };
random_line_split
app.js
'use strict'; var myTable = document.getElementById('stores'); var allStores = []; //Array for the different times of day var timesOfDay = ['6am: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: ', '8pm:']; //Constructor function function Store(na...
}; Store.prototype.calcSalesByHour = function(){ this.calcCustPerHour(); for(var i = 0; i < timesOfDay.length; i++){ var cookies = Math.ceil(this.hourlyCust[i] * this.avgCookieSale); this.hourlySales.push(cookies); this.totalSales += cookies; } return this.hourlySales; }; Store.prototype.render =...
{ var cust = Math.floor(Math.random() * (this.maxCust - this.minCust) + this.minCust); this.hourlyCust.push(cust); }
conditional_block
config.js
var args = require('yargs'); const dest = './dist'; const src = './src'; const port = 3000; const shouldWatch = args.watch; module.exports = { watch: shouldWatch, src: src, dest: dest, webpack: { entry: { bundle: src + '/bundles/bundle.js' },
} }, browserSync: { server: { baseDir: dest, port: port }//, //files: [dest + '/dist/**'] }, sass: { settings: { sourceComments: 'map', imagePath: '/img' // Used by the image-url helper } }, appx: { src: src + '/AppxManifest.xml' }, ngrok: { port: ...
output: { filename: '[name].js', path: dest + '/bundles'
random_line_split
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ):...
elm: Document | Element | string | string[], queries?: string | string[] | boolean, first?: boolean ): Element | Element[] | null { if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries)) { quer...
function findByQuery(
random_line_split
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ):...
( elm: Document | Element | string | string[], queries?: string | string[] | boolean, first?: boolean ): Element | Element[] | null { if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries)) { qu...
findByQuery
identifier_name
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ):...
export default findByQuery;
{ if (isString(elm) || Array.isArray(elm)) { first = queries as boolean; queries = elm as string | string[]; elm = document; } if (Array.isArray(queries)) { queries = queries.join(','); } const q = queries as string; return first ? elm.querySelector(q) : Array.from(elm.querySelect...
identifier_body
findByQuery.ts
import isString from 'vanillajs-helpers/isString'; /** * Find an element by given CSS selector * * @param queries - CSS selector to find elements by * @param first - Return only the first found element * @return List of found DOM elements */ function findByQuery( queries: string | string[], first: true ):...
const q = queries as string; return first ? elm.querySelector(q) : Array.from(elm.querySelectorAll(q)); } export default findByQuery;
{ queries = queries.join(','); }
conditional_block
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio 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 2 of the ## License, or (at your option) a...
fixtures = LazyDict(fixtures_loader)
"""Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)): if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data) return out
identifier_body
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio 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 2 of the ## License, or (at your option) a...
(): """Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)): if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data) return out fixtures = LazyDict(fixtures_loa...
fixtures_loader
identifier_name
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio 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 2 of the ## License, or (at your option) a...
def fixtures_loader(): """Load fixtures datasets.""" out = {} for fixture in fixtures_proxy: for data in getattr(fixture, '__all__', dir(fixture)): if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data) return out fixtures = ...
fixtures_proxy = RegistryProxy( 'fixtures', ModuleAutoDiscoveryRegistry, 'fixtures')
random_line_split
registry.py
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2014 CERN. ## ## Invenio 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 2 of the ## License, or (at your option) a...
return out fixtures = LazyDict(fixtures_loader)
if data[-4:] != 'Data' or data in out: continue out[data] = getattr(fixture, data)
conditional_block
editor_plugin_src.js
(cn) { switch (cn) { case "flash": return tinyMCE.getButtonHTML(cn, 'lang_flash_desc', '{$pluginurl}/images/flash.gif', 'mceFlash'); } return ""; }, execCommand : function(editor_id, element, command, user_interface, value) { // Handle commands switch (command) { case "mceFlash": ...
tinyMCE.switchClass(editor_id + '_flash', 'mceButtonSelected'); return true; }
conditional_block
editor_plugin_src.js
Systems', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_flash.html', version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion }; }, initInstance : function(inst) { if (!tinyMCE.settings['flash_skip_plugin_css']) tinyMCE.importCSS(...
imgs[i].setAttribute('alt', src); imgs[i].setAttribute('title', src); } } } break; case "get_from_editor_dom": var imgs = content.getElementsByTagName("img"); for (var i=0; i<imgs.length; i++) { if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") { ...
if (tinyMCE.getParam('convert_urls')) src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);");
random_line_split
DataTypeMapIntFloat.py
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def
(xs): return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', ...
to_objectset
identifier_name
DataTypeMapIntFloat.py
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual
return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') =...
c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs):
random_line_split
DataTypeMapIntFloat.py
#!/usr/bin/env python import sys import hyperdex.client from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs):
assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}}
return set([frozenset(x.items()) for x in xs])
identifier_body
adminMenu.js
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *
* * 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 Licen...
* https://www.apache.org/licenses/LICENSE-2.0
random_line_split
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `s...
}, remove: (key: string, scope: unknown): void => { strings.delete(key); }, keys: (scope: unknown, target: unknown): string[] => { return Array.from(strings.keys()); }, logStorage: (): void => { console.log('logStorage: not implemented'); }, migrate: (): Promise<vo...
{ strings.set(key, value.toString()); }
conditional_block
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `s...
// we create a new storage for every session, we do not persist it, // so we return `true`. return true; }, flush: (reason?: unknown): Promise<void> => { // we do not implement this return Promise.resolve(undefined); }, }; } let overrideServices: monacoTypes.editor.IEditorO...
isNew: (scope: unknown): boolean => {
random_line_split
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `s...
(): monacoTypes.editor.IEditorOverrideServices { // only have one instance of this for every query editor if (overrideServices === null) { overrideServices = { storageService: makeStorageService(), }; } return overrideServices; }
getOverrideServices
identifier_name
getOverrideServices.ts
import { monacoTypes } from '@grafana/ui'; // this thing here is a workaround in a way. // what we want to achieve, is that when the autocomplete-window // opens, the "second, extra popup" with the extra help, // also opens automatically. // but there is no API to achieve it. // the way to do it is to implement the `s...
getBoolean: (key: string, scope: unknown, fallbackValue?: boolean): boolean | undefined => { const val = strings.get(key); if (val !== undefined) { // the interface-docs say the value will be converted // to a boolean but do not specify how, so we improvise return val === 'true';...
{ // we need to return an object that fulfills this interface: // https://github.com/microsoft/vscode/blob/ff1e16eebb93af79fd6d7af1356c4003a120c563/src/vs/platform/storage/common/storage.ts#L37 // unfortunately it is not export from monaco-editor const strings = new Map<string, string>(); // we want this to...
identifier_body
match-vec-rvalue.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); } } }
main
identifier_name
match-vec-rvalue.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} }
{ assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); }
conditional_block
match-vec-rvalue.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ match vec!(1, 2, 3) { x => { assert_eq!(x.len(), 3); assert_eq!(x[0], 1); assert_eq!(x[1], 2); assert_eq!(x[2], 3); } } }
identifier_body
match-vec-rvalue.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert_eq!(x[2], 3); } } }
assert_eq!(x[0], 1); assert_eq!(x[1], 2);
random_line_split
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer
class AccountCreateView(generics.CreateAPIView): queryset = Account.objects.all() serializer_class = AccountCreateSerializer permission_classes = [permissions.AllowAny] class AccountListView(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer permissio...
# Create your views here.
random_line_split
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.Create...
(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class Accoun...
AccountRetrieveView
identifier_name