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 |
|---|---|---|---|---|
index.ts | // most of the cycle import error is caused by @/types, which is fine
// since @/types is used only when TS compiler, will not effect production code
/* eslint-disable import/no-cycle */
/*
* utils functiosn
*/
export { default as asyncSuit } from './async/index'
export { buildLog } from './logger'
export { defau... | export {
parseURL,
ssrParseURL,
akaTranslate,
getParameterByName,
getQueryFromUrl,
queryStringToJSON,
serializeQuery,
parseDomain,
getRoutePathList,
getRouteMainPath,
markRoute,
} from './route'
export {
pluggedIn,
storePlug,
markStates,
flashState,
meteorState,
toJS,
updateEditing,... | random_line_split | |
YearPickerRenderer.js | /*!
* ${copyright}
*/
sap.ui.define(['sap/ui/unified/calendar/CalendarDate', 'sap/ui/core/date/UniversalDate'],
function(CalendarDate, UniversalDate) {
"use strict";
/*
* Inside the YearPickerRenderer CalendarDate objects are used. But in the API JS dates are used.
* So conversion must be done on API functio... | else {
mAccProps["selected"] = false;
}
if (!bEnabled) {
oRm.addClass("sapUiCalItemDsbl"); // year disabled
mAccProps["disabled"] = true;
}
oRm.writeAttribute("tabindex", "-1");
oRm.writeAttribute("data-sap-year-start", sYyyymmdd);
oRm.addStyle("width", sWidth);
oRm.writeClasses();
... | {
oRm.addClass("sapUiCalItemSel");
mAccProps["selected"] = true;
} | conditional_block |
YearPickerRenderer.js | /*!
* ${copyright}
*/
sap.ui.define(['sap/ui/unified/calendar/CalendarDate', 'sap/ui/core/date/UniversalDate'],
function(CalendarDate, UniversalDate) {
"use strict";
/*
* Inside the YearPickerRenderer CalendarDate objects are used. But in the API JS dates are used.
* So conversion must be done on API functio... | if (!oFirstDate.isSame(oDate)) {
oDate = oFirstDate;
bEnabledCheck = true;
}
if (iColumns > 0) {
sWidth = ( 100 / iColumns ) + "%";
} else {
sWidth = ( 100 / iYears ) + "%";
}
for ( var i = 0; i < iYears; i++) {
var sYyyymmdd = oYP._oFormatYyyymmdd.format(oDate.toUTCJSDate(), true);
var ... | oDate.setYear(oDate.getYear() - Math.floor(iYears / 2));
var bEnabledCheck = false; // check for disabled years only needed if borders touched
var oFirstDate = oYP._checkFirstDate(oDate); | random_line_split |
colors.rs | //! Color definitions.
//!
//! This module should contain all colors used in the game. Later on, we could
//! replace it with a customizeable version, where people could write themes
//! (e.g. in TOML or YAML format).
//!
//! Make sure to contain only semantic names (e.g. "primary" or "background",
//! not "red" or "gr... | {
pub primary: [f32; 4],
pub secondary: [f32; 4],
}
pub const PLAYERS: [Player; 3] = [
Player {
primary: ORANGE,
secondary: YELLOW,
},
Player {
primary: RED,
secondary: ORANGE,
},
Player {
primary: BLUE,
secondary: LIGHT_BLUE,
},
];
| Player | identifier_name |
colors.rs | //! Color definitions.
//!
//! This module should contain all colors used in the game. Later on, we could
//! replace it with a customizeable version, where people could write themes
//! (e.g. in TOML or YAML format).
//!
//! Make sure to contain only semantic names (e.g. "primary" or "background",
//! not "red" or "gr... | pub const LIGHT_BLUE: [f32; 4] = [0.22, 0.22, 1.0, 1.0];
pub const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
pub struct Player {
pub primary: [f32; 4],
pub secondary: [f32; 4],
}
pub const PLAYERS: [Player; 3] = [
Player {
primary: ORANGE,
secondary: YELLOW,
},
Player {
primar... | pub const TRANSPARENT_WHITE: [f32; 4] = [1.0, 1.0, 1.0, 0.2];
pub const YELLOW: [f32; 4] = [1.0, 1.0, 0.22, 1.0];
pub const ORANGE: [f32; 4] = [1.0, 0.61, 0.22, 1.0];
pub const RED: [f32; 4] = [1.0, 0.22, 0.22, 1.0]; | random_line_split |
simple_packet.rs | use crate::errors::PcapError;
use byteorder::{ByteOrder, ReadBytesExt};
use std::borrow::Cow;
use derive_into_owned::IntoOwned;
/// The Simple Packet Block (SPB) is a lightweight container for storing the packets coming from the network.
/// Its presence is optional.
#[derive(Clone, Debug, IntoOwned)]
pub struct Simp... | if slice.len() < 4 {
return Err(PcapError::InvalidField("SimplePacketBlock: block length < 4"));
}
let original_len = slice.read_u32::<B>()?;
let packet = SimplePacketBlock {
original_len,
data: Cow::Borrowed(slice)
};
Ok((&[], packet... | random_line_split | |
simple_packet.rs | use crate::errors::PcapError;
use byteorder::{ByteOrder, ReadBytesExt};
use std::borrow::Cow;
use derive_into_owned::IntoOwned;
/// The Simple Packet Block (SPB) is a lightweight container for storing the packets coming from the network.
/// Its presence is optional.
#[derive(Clone, Debug, IntoOwned)]
pub struct Simp... | <B: ByteOrder>(mut slice: &'a [u8]) -> Result<(&'a [u8], Self), PcapError> {
if slice.len() < 4 {
return Err(PcapError::InvalidField("SimplePacketBlock: block length < 4"));
}
let original_len = slice.read_u32::<B>()?;
let packet = SimplePacketBlock {
original_l... | from_slice | identifier_name |
simple_packet.rs | use crate::errors::PcapError;
use byteorder::{ByteOrder, ReadBytesExt};
use std::borrow::Cow;
use derive_into_owned::IntoOwned;
/// The Simple Packet Block (SPB) is a lightweight container for storing the packets coming from the network.
/// Its presence is optional.
#[derive(Clone, Debug, IntoOwned)]
pub struct Simp... |
let original_len = slice.read_u32::<B>()?;
let packet = SimplePacketBlock {
original_len,
data: Cow::Borrowed(slice)
};
Ok((&[], packet))
}
}
| {
return Err(PcapError::InvalidField("SimplePacketBlock: block length < 4"));
} | conditional_block |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | line: String::new(),
lazyness: ReaderLazyness::Lazy,
file_size: metadata.len(),
chars_read: 0,
nblines_read: 0,
}
}
/// Returns a muta
ble reference on the record corresponding to the line read. **next()** returns **None**
/// if EOF.
... | or reading
let bufreader = match File::open(&rbf_file) {
// if ok, create a new BufReader to read the file line by line
Ok(f) => match layout.rec_length {
0 => BufReader::new(f),
_ => BufReader::with_capacity(layout.rec_length+1, f),
},
... | identifier_body |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | //! for (i, l) in greek.chars().enumerate() {
//! let fname = format!("G{}", i+1);
//! assert_eq!(rec.get_value(&fname), l.to_string().repeat(i+1));
//! }
//! },
//! "DP" => {
//! assert_e... | random_line_split | |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | aderLazyness) {
self.lazyness = lazyness;
}
}
| lazyness: Re | identifier_name |
reader.rs | //! Represents a way to read a record-based file by mapping each read line to a record. The mapping between
//! the data from the file and the record name is made by the `mapper` function.
//!
//! # Examples
//! ```rust
//! use rbf::record::{AsciiMode, UTF8Mode};
//! use rbf::layout::Layout;
//! use rbf::reade... | self.chars_read = chars_read;
self.nblines_read += 1;
},
// error reading bytes
Err(why) => panic!("error {} when reading file {}", why.description(), self.rbf_file),
};
// get the record ID using mapper
... | return None;
} else {
| conditional_block |
polyfills.ts | /**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported... |
})()
| {
Window.prototype.createImageBitmap = function(imageData):Promise<any>{
return new Promise((resolve,reject)=>{
let canvas=document.createElement('canvas');
canvas.width=imageData.width;
canvas.height=imageData.height;
let c... | conditional_block |
polyfills.ts | /**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported... |
/** ALL Firefox browsers require the following to support `@angular/animation`. **/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/***************************************************************************************************
* Zone JS is required by Angular itself.
*/
impor... | import 'core-js/es6/reflect';
import 'core-js/es7/reflect'; | random_line_split |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... |
}
}
fn rho_pollard_factor(num: u64, factors: &mut Vec<u64>) {
if is_prime(num) {
factors.push(num);
return;
}
let divisor = rho_pollard_find_divisor(num);
rho_pollard_factor(divisor, factors);
rho_pollard_factor(num / divisor, factors);
}
fn table_division(mut num: u64, factor... | {
return d;
} | conditional_block |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... | let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.parse(args);
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
}
}
} else {
f... | pub fn uumain(args: Vec<String>) -> i32 { | random_line_split |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... | (mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind... | gcd | identifier_name |
factor.rs | #![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <t.jameson.little@gmail.com>
* (c) Wiktor Kuropatwa <wiktor.kuropatwa@gmail.com>
* 20150223 added Pollard rho method implementation
* (c) kwantam <kwantam@gmail.com>
* 20150429 sped up trial division ... |
pub fn uumain(args: Vec<String>) -> i32 {
let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP)
.parse(args);
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
... | {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
} | identifier_body |
Pokemon.js | const { InventoryError,
NotFoundError } = require('../../errors')
const checkExists = (data) => {
return (entity) => {
if (!entity) throw new NotFoundError(`${data} not found`)
return entity
}
}
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('Pokemon', {
name: DataTy... | this.stock -= quantity
return this.save()
}
Pokemon.prototype.increaseStock = function (quantity) {
this.stock += quantity
return this.save()
}
return Pokemon
} | if (this.stock < quantity) {
return Promise.reject(new InventoryError(this.name, this.stock))
}
| random_line_split |
Pokemon.js | const { InventoryError,
NotFoundError } = require('../../errors')
const checkExists = (data) => {
return (entity) => {
if (!entity) throw new NotFoundError(`${data} not found`)
return entity
}
}
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('Pokemon', {
name: DataTy... |
this.stock -= quantity
return this.save()
}
Pokemon.prototype.increaseStock = function (quantity) {
this.stock += quantity
return this.save()
}
return Pokemon
}
| {
return Promise.reject(new InventoryError(this.name, this.stock))
} | conditional_block |
foxnews.py | from __future__ import unicode_literals
import re
from .amp import AMPIE
from .common import InfoExtractor
class FoxNewsIE(AMPIE):
IE_NAME = 'foxnews'
IE_DESC = 'Fox News and Fox Business Video'
_VALID_URL = r'https?://(?P<host>video\.(?:insider\.)?fox(?:news|business)\.com)/v/(?:video-embed\.html\?vide... | 'upload_date': '20110503',
'thumbnail': r're:^https?://.*\.jpg$',
},
},
{
'url': 'http://video.foxnews.com/v/3922535568001/rep-luis-gutierrez-on-if-obamas-immigration-plan-is-legal/#sp=show-clips',
'md5': '5846c64a1ea05ec78175421b8323e2... | 'timestamp': 1304411491, | random_line_split |
foxnews.py | from __future__ import unicode_literals
import re
from .amp import AMPIE
from .common import InfoExtractor
class FoxNewsIE(AMPIE):
IE_NAME = 'foxnews'
IE_DESC = 'Fox News and Fox Business Video'
_VALID_URL = r'https?://(?P<host>video\.(?:insider\.)?fox(?:news|business)\.com)/v/(?:video-embed\.html\?vide... |
class FoxNewsArticleIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?(?:insider\.)?foxnews\.com/(?!v)([^/]+/)+(?P<id>[a-z-]+)'
IE_NAME = 'foxnews:article'
_TESTS = [{
# data-video-id
'url': 'http://www.foxnews.com/politics/2016/09/08/buzz-about-bud-clinton-camp-denies-claims-wore-ear... | host, video_id = re.match(self._VALID_URL, url).groups()
info = self._extract_feed_info(
'http://%s/v/feed/video/%s.js?template=fox' % (host, video_id))
info['id'] = video_id
return info | identifier_body |
foxnews.py | from __future__ import unicode_literals
import re
from .amp import AMPIE
from .common import InfoExtractor
class | (AMPIE):
IE_NAME = 'foxnews'
IE_DESC = 'Fox News and Fox Business Video'
_VALID_URL = r'https?://(?P<host>video\.(?:insider\.)?fox(?:news|business)\.com)/v/(?:video-embed\.html\?video_id=)?(?P<id>\d+)'
_TESTS = [
{
'url': 'http://video.foxnews.com/v/3937480/frozen-in-time/#sp=show-cl... | FoxNewsIE | identifier_name |
foxnews.py | from __future__ import unicode_literals
import re
from .amp import AMPIE
from .common import InfoExtractor
class FoxNewsIE(AMPIE):
IE_NAME = 'foxnews'
IE_DESC = 'Fox News and Fox Business Video'
_VALID_URL = r'https?://(?P<host>video\.(?:insider\.)?fox(?:news|business)\.com)/v/(?:video-embed\.html\?vide... |
return self.url_result(
FoxNewsIE._extract_urls(webpage)[0], FoxNewsIE.ie_key())
| return self.url_result(
'http://video.foxnews.com/v/' + video_id, FoxNewsIE.ie_key()) | conditional_block |
test_provider.py | import numpy as np
from esdl.cube_provider import CubeSourceProvider
from esdl.cube_config import CubeConfig
class TestCubeSourceProvider(CubeSourceProvider):
"""
CubeSourceProvider implementation used for testing cube generation without any source files.
The following usage generates a cube with two var... |
@property
def variable_descriptors(self):
return {
self._variable_name: {
'data_type': np.float32,
'fill_value': np.nan,
'scale_factor': 1.0,
'add_offset': 0.0,
}
}
def compute_variable_images(self, pe... | return 0, 0, self.cube_config.grid_width, self.cube_config.grid_height | identifier_body |
test_provider.py | import numpy as np
from esdl.cube_provider import CubeSourceProvider
from esdl.cube_config import CubeConfig
class TestCubeSourceProvider(CubeSourceProvider):
"""
CubeSourceProvider implementation used for testing cube generation without any source files.
The following usage generates a cube with two var... | (self, period_start, period_end):
self._value += 0.1
image_width = self.cube_config.grid_width
image_height = self.cube_config.grid_height
image_shape = (image_height, image_width)
return {
self._variable_name: np.full(image_shape, self._value, dtype=np.float32)
... | compute_variable_images | identifier_name |
test_provider.py | import numpy as np
from esdl.cube_provider import CubeSourceProvider
from esdl.cube_config import CubeConfig
class TestCubeSourceProvider(CubeSourceProvider):
"""
CubeSourceProvider implementation used for testing cube generation without any source files.
The following usage generates a cube with two var... | pass | }
def close(self): | random_line_split |
qu-EC.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number... |
export default [
'qu-EC',
[
['a.m.', 'p.m.'],
,
],
,
[
['D', 'L', 'M', 'X', 'J', 'V', 'S'], ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sab'],
['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sab']
],
,
[
['... | {
return 5;
} | identifier_body |
qu-EC.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number... | 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre',
'Octubre', 'Noviembre', 'Diciembre'
]
],
,
[
['BCE', 'dC'],
['BCE', 'd.C.'],
],
1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM, y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'... | ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Set', 'Oct', 'Nov', 'Dic'],
[ | random_line_split |
qu-EC.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function | (n: number): number {
return 5;
}
export default [
'qu-EC',
[
['a.m.', 'p.m.'],
,
],
,
[
['D', 'L', 'M', 'X', 'J', 'V', 'S'], ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sab'],
['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
['Dom', 'Lun', 'Mar', 'Mié', 'Jue'... | plural | identifier_name |
t1Lib.py |
import os
try:
try:
from Carbon import Res
except ImportError:
import Res # MacPython < 2.2
except ImportError:
haveMacSupport = 0
else:
haveMacSupport = 1
import MacOS
class T1Error(Exception): pass
class T1Font:
"""Type 1 font class.
Uses a minimal interpeter that suppor... |
# decryption tools
EEXECBEGIN = "currentfile eexec"
EEXECEND = '0' * 64
EEXECINTERNALEND = "currentfile closefile"
EEXECBEGINMARKER = "%-- eexec start\r"
EEXECENDMARKER = "%-- eexec end\r"
_ishexRE = re.compile('[0-9A-Fa-f]*$')
def isHex(text):
return _ishexRE.match(text) is not None
def decry... | chunks = findEncryptedChunks(data)
f = open(path, "wb")
try:
hexlinelen = HEXLINELENGTH / 2
for isEncrypted, chunk in chunks:
if isEncrypted:
code = 2
else:
code = 1
if code == 2 and dohex:
while chunk:
f.write(eexec.hexString(chunk[:hexlinelen]))
f.write('\r')
chu... | identifier_body |
t1Lib.py |
import os
try:
try:
from Carbon import Res
except ImportError:
import Res # MacPython < 2.2
except ImportError:
haveMacSupport = 0
else:
haveMacSupport = 1
import MacOS
class T1Error(Exception): pass
class T1Font:
"""Type 1 font class.
Uses a minimal interpeter that suppor... |
else:
raise T1Error, 'bad chunk code: ' + `code`
finally:
Res.CloseResFile(resRef)
data = string.join(data, '')
assertType1(data)
return data
def readPFB(path, onlyHeader=0):
"""reads a PFB font file, returns raw data"""
f = open(path, "rb")
data = []
while 1:
if f.read(1) <> chr(128):... | pass # comment, ignore
| conditional_block |
t1Lib.py |
import os
try:
try:
from Carbon import Res
except ImportError:
import Res # MacPython < 2.2
except ImportError:
haveMacSupport = 0
else:
haveMacSupport = 1
import MacOS
class T1Error(Exception): pass
class T1Font:
"""Type 1 font class.
Uses a minimal interpeter that suppor... | (path, data, kind='OTHER', dohex=0):
assertType1(data)
kind = string.upper(kind)
try:
os.remove(path)
except os.error:
pass
err = 1
try:
if kind == 'LWFN':
writeLWFN(path, data)
elif kind == 'PFB':
writePFB(path, data)
else:
writeOther(path, data, dohex)
err = 0
finally:
i... | write | identifier_name |
t1Lib.py | re
import os
try:
try:
from Carbon import Res
except ImportError:
import Res # MacPython < 2.2
except ImportError:
haveMacSupport = 0
else:
haveMacSupport = 1
import MacOS
class T1Error(Exception): pass
class T1Font:
"""Type 1 font class.
Uses a minimal interpeter that sup... | have a .draw() method that supports the Pen protocol, and will
have an attribute named 'width', but only *after* the .draw() method
has been called.
In the case of Type 1, the GlyphSet is simply the CharStrings dict.
"""
return self["CharStrings"]
def __getitem__(self, key):
if not hasattr(... | """Return a generic GlyphSet, which is a dict-like object
mapping glyph names to glyph objects. The returned glyph objects
| random_line_split |
navbar.component.ts | import {Component, Input} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import {ROUTER_DIRECTIVES, Router} from '@angular/router-deprecated';
import {AuthService} from '../common/auth.service';
@Component({
selector: 'todo-navbar',
templateUrl: 'app/navbar/navbar.component.html',
direct... |
getName() {
console.log('getName');
return this.name;
}
logout($event: Event) {
$event.preventDefault();
this._authService.logout();
this._router.navigateByUrl('/');
}
isLoggedIn() {
return Boolean(this.name);
}
}
| {
this._authService.profile.subscribe(profile => this.name = profile && profile.name);
} | identifier_body |
navbar.component.ts | import {Component, Input} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import {ROUTER_DIRECTIVES, Router} from '@angular/router-deprecated';
import {AuthService} from '../common/auth.service';
@Component({
selector: 'todo-navbar',
templateUrl: 'app/navbar/navbar.component.html',
direct... | ($event: Event) {
$event.preventDefault();
this._authService.logout();
this._router.navigateByUrl('/');
}
isLoggedIn() {
return Boolean(this.name);
}
}
| logout | identifier_name |
navbar.component.ts | import {Component, Input} from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import {ROUTER_DIRECTIVES, Router} from '@angular/router-deprecated';
import {AuthService} from '../common/auth.service';
@Component({
selector: 'todo-navbar',
templateUrl: 'app/navbar/navbar.component.html',
direct... | this._authService.logout();
this._router.navigateByUrl('/');
}
isLoggedIn() {
return Boolean(this.name);
}
} |
logout($event: Event) {
$event.preventDefault(); | random_line_split |
code.py | ,
'1':0x31,
'2':0x32,
'3':0x33,
'4':0x34,
'5':0x35,
'6':0x36,
'7':0x37,
'8':0x38,
'9':0x39,
'a':0x41,
'b':0x42,
'c':0x43,
'd':0x44,
'e':0x45,
'f':0x46,
'g':0x47,
'h':0x48,
'i':0x49,
'j':0x4A,
'k':0x4B,
'l':0x4C,
'm':0x4D,
'n':0x4E,
'o':0x4F,
'p'... | mousePos((628, 146))
mouseClick()
time.sleep(.1)
#Spacebar to skip intro
time.sleep(.1)
pressKey('spacebar')
#location of first menu
mousePos((628, 146))
mouseClick()
time.sleep(.1) | identifier_body | |
code.py | 0x49,
'j':0x4A,
'k':0x4B,
'l':0x4C,
'm':0x4D,
'n':0x4E,
'o':0x4F,
'p':0x50,
'q':0x51,
'r':0x52,
's':0x53,
't':0x54,
'u':0x55,
'v':0x56,
'w':0x57,
'x':0x58,
'y':0x59,
'z':0x5A,
'numpad_0':0x60,
'numpad_1':0x61,
'numpad_2':0x62,
'numpad_3':0x63,
'numpad_4'... | mousePos(POSITIONS[pos]) #place mouse at key position for debugging | conditional_block | |
code.py | 'esc':0x1B,
'spacebar':0x20,
'page_up':0x21,
'page_down':0x22,
'end':0x23,
'home':0x24,
'left_arrow':0x25,
'up_arrow':0x26,
'right_arrow':0x27,
'down_arrow':0x28,
'select':0x29,
'print':0x2A,
'execute':0x2B,
'print_screen':0x2C,
'ins':0x2D,
'del':0x2E,
'help':0x2F,
'0... | 'd': (493, 530),
'f': (584, 529),
'g': (670, 525),
'h': (764, 531),
'j': (861, 536),
'k': (942, 532),
'l': (1035, 524),
'z': (366, 613),
'x': (454, 609),
'c': (542, 618),
'v': (640, 615),
'b': (724, 605),
'n': (818, 614),
'm': (908, 613)}
#do a leftclick
def mou... | 'o': (990, 451),
'p': (1081, 450),
'a': (318, 532),
's': (405, 528), | random_line_split |
code.py | 'esc':0x1B,
'spacebar':0x20,
'page_up':0x21,
'page_down':0x22,
'end':0x23,
'home':0x24,
'left_arrow':0x25,
'up_arrow':0x26,
'right_arrow':0x27,
'down_arrow':0x28,
'select':0x29,
'print':0x2A,
'execute':0x2B,
'print_screen':0x2C,
'ins':0x2D,
'del':0x2E,
'help':0x2F,
'0'... | ():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
print "Left Click." #completely optional. But nice for debugging purposes.
#position mouse at cords (x, y)
def mousePos(cord):
win32api.SetCursorPos((pad_x + cord[0], pad_y + cord[1]))... | mouseClick | identifier_name |
dropUploader.ts | import path = require('path');
import fs = require('fs');
import zlib = require('zlib');
import stream = require('stream');
import crypto = require('crypto');
import Q = require("q");
import shell = require("shelljs");
import ctxm = require('../../../context');
import cm = require('../../../common');
import fchelperm =... | (filePath): Q.Promise<number> {
_ensureTracing(_ctx, '_getFileSize');
_trace.write('fileSize for: ' + filePath);
var defer = Q.defer<number>();
var l = 0;
var rs = fs.createReadStream(filePath);
rs.on('readable', function() {
var chunk;
while (null !== (chunk = rs.read())) {
... | _getFileSize | identifier_name |
dropUploader.ts | import path = require('path');
import fs = require('fs');
import zlib = require('zlib');
import stream = require('stream');
import crypto = require('crypto');
import Q = require("q");
import shell = require("shelljs");
import ctxm = require('../../../context');
import cm = require('../../../common');
import fchelperm =... |
else {
var item: ifm.FileContainerItemInfo = <ifm.FileContainerItemInfo>{
fullPath: filePath,
containerItem: <fcifm.FileContainerItem>{
containerId: _containerId,
itemType: fcifm.ContainerItemType.File,
path: containerPath
},
uploadHeader... | {
return _uploadZip(filePath, size, containerPath);
} | conditional_block |
dropUploader.ts | import path = require('path');
import fs = require('fs');
import zlib = require('zlib');
import stream = require('stream');
import crypto = require('crypto');
import Q = require("q");
import shell = require("shelljs");
import ctxm = require('../../../context');
import cm = require('../../../common');
import fchelperm =... | };
_trace.state('item', item);
return _ctx.service.uploadFileToContainer(_containerId, item);
})
}
function _uploadFile(filePath) {
_ensureTracing(_ctx, '_uploadFile');
var info = <any>{};
var containerPath = path.join(_containerRoot, filePath.substring(_stagingFolder.length + 1));
_ctx.info(contai... | {
_ensureTracing(_ctx, '_uploadZip');
var info = <any>{};
return _zipToTemp(filePath)
.then((zipPath) => {
info.zipPath = zipPath;
return _getFileSize(zipPath);
})
.then((zipSize) => {
_trace.write(info.zipPath + ':' + zipSize);
var item: ifm.FileContainerItemInfo = <ifm.FileContainerItemInfo>{
... | identifier_body |
dropUploader.ts | import path = require('path');
import fs = require('fs');
import zlib = require('zlib');
import stream = require('stream');
import crypto = require('crypto');
import Q = require("q");
import shell = require("shelljs");
import ctxm = require('../../../context');
import cm = require('../../../common');
import fchelperm =... | }
return defer.promise;
}
function _uploadZip(filePath: string, fileSize: number, containerPath: string) {
_ensureTracing(_ctx, '_uploadZip');
var info = <any>{};
return _zipToTemp(filePath)
.then((zipPath) => {
info.zipPath = zipPath;
return _getFileSize(zipPath);
})
.then((zipSize) => {
_trace.write(... | }
catch (err) {
defer.reject(err); | random_line_split |
index.d.ts |
export class | {
private strings: string[];
/**
* The SQL Statement for [node-postgres](https://www.npmjs.com/package/pg)
*/
text: string;
/**
* The SQL Statement for [Sequelize](https://www.npmjs.com/package/sequelize)
*/
query: string
/**
* The SQL Statement for [mysql](https://www.npmjs.com/package/... | SQLStatement | identifier_name |
index.d.ts | export class SQLStatement {
private strings: string[];
/** | * The SQL Statement for [node-postgres](https://www.npmjs.com/package/pg)
*/
text: string;
/**
* The SQL Statement for [Sequelize](https://www.npmjs.com/package/sequelize)
*/
query: string
/**
* The SQL Statement for [mysql](https://www.npmjs.com/package/mysql)
*/
sql: string;
/**
* ... | random_line_split | |
_wav.py | # -*- coding: utf-8 -*-
"""WAV file IO functions
"""
import numpy as np
from scipy.io import wavfile
from os import path as op
import warnings
from .._utils import verbose_dec, logger, _has_scipy_version
@verbose_dec
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fna... | (pre, data, dtype):
"""Helper to print WAV info"""
logger.info('{0} WAV file with {1} channel{3} and {2} samples '
'(format {4})'.format(pre, data.shape[0], data.shape[1],
's' if data.shape[0] != 1 else '',
dtype))
def... | _print_wav_info | identifier_name |
_wav.py | # -*- coding: utf-8 -*-
"""WAV file IO functions
"""
import numpy as np
from scipy.io import wavfile
from os import path as op
import warnings
from .._utils import verbose_dec, logger, _has_scipy_version
@verbose_dec
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fna... |
@verbose_dec
def write_wav(fname, data, fs, dtype=np.int16, overwrite=False, verbose=None):
"""Write a WAV file
Parameters
----------
fname : str
Filename to save as.
data : array
The data to save.
fs : int
The sample rate of the data.
dtype : numpy dtype
T... | random_line_split | |
_wav.py | # -*- coding: utf-8 -*-
"""WAV file IO functions
"""
import numpy as np
from scipy.io import wavfile
from os import path as op
import warnings
from .._utils import verbose_dec, logger, _has_scipy_version
@verbose_dec
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fna... |
data = np.atleast_2d(data)
if np.dtype(dtype).kind not in ['i', 'f']:
raise TypeError('dtype must be integer or float')
if np.dtype(dtype).kind == 'f':
if not _has_scipy_version('0.13'):
raise RuntimeError('cannot write float datatype unless '
'sci... | fs = int(fs)
warnings.warn('Warning: sampling rate is being cast to integer and '
'may be truncated.') | conditional_block |
_wav.py | # -*- coding: utf-8 -*-
"""WAV file IO functions
"""
import numpy as np
from scipy.io import wavfile
from os import path as op
import warnings
from .._utils import verbose_dec, logger, _has_scipy_version
@verbose_dec
def read_wav(fname, verbose=None):
"""Read in a WAV file
Parameters
----------
fna... |
def _get_dtype_norm(dtype):
"""Helper to get normalization factor for a given datatype"""
if np.dtype(dtype).kind == 'i':
info = np.iinfo(dtype)
maxval = min(-info.min, info.max)
else: # == 'f'
maxval = 1.0
return maxval
| """Helper to print WAV info"""
logger.info('{0} WAV file with {1} channel{3} and {2} samples '
'(format {4})'.format(pre, data.shape[0], data.shape[1],
's' if data.shape[0] != 1 else '',
dtype)) | identifier_body |
index.d.ts | // Type definitions for omggif 1.0
// Project: https://github.com/deanm/omggif
// Definitions by: Florian Keller <https://github.com/ffflorian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="node" />
export interface GifOptions {
background?: nu... | {
height: number;
width: number;
constructor(buf: Buffer, width: number, height: number, gopts?: GifOptions);
addFrame(x: number, y: number, w: number, h: number, indexed_pixels: number[], opts?: FrameOptions): number;
end(): number;
getOutputBuffer(): Buffer;
getOutputBufferPosition(): n... | GifWriter | identifier_name |
index.d.ts | // Type definitions for omggif 1.0
// Project: https://github.com/deanm/omggif
// Definitions by: Florian Keller <https://github.com/ffflorian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="node" />
export interface GifOptions {
background?: nu... | setOutputBuffer(v: Buffer): void;
setOutputBufferPosition(v: number): void;
}
export class GifReader {
height: number;
width: number;
constructor(buf: Buffer);
decodeAndBlitFrameBGRA(frame_num: number, pixels: number[] | Uint8Array | Uint8ClampedArray): void;
decodeAndBlitFrameRGBA(frame_... | random_line_split | |
mod.py | # the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for... | # Copyright (C) 2008-2010 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by | random_line_split | |
mod.py | # Copyright (C) 2008-2010 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that... | (self):
return -1
# vim: et sts=4 sw=4
| get_bitrate | identifier_name |
mod.py | # Copyright (C) 2008-2010 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that... |
def get_length(self):
try:
return self.mutagen['__length']
except KeyError:
return -1
def get_bitrate(self):
return -1
# vim: et sts=4 sw=4
| self.mutagen = {} | conditional_block |
mod.py | # Copyright (C) 2008-2010 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that... |
# vim: et sts=4 sw=4
| return -1 | identifier_body |
multi.py | import numpy as np
def multiprod(A, B):
"""
Inspired by MATLAB multiprod function by Paolo de Leva. A and B are
assumed to be arrays containing M matrices, that is, A and B have
dimensions A: (M, N, P), B:(M, P, Q). multiprod multiplies each matrix
in A with the corresponding matrix in B, using ma... | # Inspired by MATLAB multiskew function by Nicholas Boumal.
return 0.5 * (A - multitransp(A))
def multieye(k, n):
# Creates a k x n x n array containing k (n x n) identity matrices.
return np.tile(np.eye(n), (k, 1, 1))
def multilog(A, pos_def=False):
if not pos_def:
raise NotImplementedE... | # Inspired by MATLAB multisym function by Nicholas Boumal.
return 0.5 * (A + multitransp(A))
def multiskew(A): | random_line_split |
multi.py | import numpy as np
def multiprod(A, B):
"""
Inspired by MATLAB multiprod function by Paolo de Leva. A and B are
assumed to be arrays containing M matrices, that is, A and B have
dimensions A: (M, N, P), B:(M, P, Q). multiprod multiplies each matrix
in A with the corresponding matrix in B, using ma... |
# Computes the logm of each matrix in an array containing k positive
# definite matrices. This is much faster than scipy.linalg.logm even
# for a single matrix. Could potentially be improved further.
l, v = np.linalg.eigh(A)
l = np.expand_dims(np.log(l), axis=-1)
return multiprod(v, l * multit... | raise NotImplementedError | conditional_block |
multi.py | import numpy as np
def multiprod(A, B):
"""
Inspired by MATLAB multiprod function by Paolo de Leva. A and B are
assumed to be arrays containing M matrices, that is, A and B have
dimensions A: (M, N, P), B:(M, P, Q). multiprod multiplies each matrix
in A with the corresponding matrix in B, using ma... |
def multisym(A):
# Inspired by MATLAB multisym function by Nicholas Boumal.
return 0.5 * (A + multitransp(A))
def multiskew(A):
# Inspired by MATLAB multiskew function by Nicholas Boumal.
return 0.5 * (A - multitransp(A))
def multieye(k, n):
# Creates a k x n x n array containing k (n x n) id... | """
Inspired by MATLAB multitransp function by Paolo de Leva. A is assumed to
be an array containing M matrices, each of which has dimension N x P.
That is, A is an M x N x P array. Multitransp then returns an array
containing the M matrix transposes of the matrices in A, each of which
will be P x N... | identifier_body |
multi.py | import numpy as np
def multiprod(A, B):
"""
Inspired by MATLAB multiprod function by Paolo de Leva. A and B are
assumed to be arrays containing M matrices, that is, A and B have
dimensions A: (M, N, P), B:(M, P, Q). multiprod multiplies each matrix
in A with the corresponding matrix in B, using ma... | (A):
# Inspired by MATLAB multisym function by Nicholas Boumal.
return 0.5 * (A + multitransp(A))
def multiskew(A):
# Inspired by MATLAB multiskew function by Nicholas Boumal.
return 0.5 * (A - multitransp(A))
def multieye(k, n):
# Creates a k x n x n array containing k (n x n) identity matrices... | multisym | identifier_name |
DateEditor.tsx | import i18next from "i18next"
import {ExpressionObj} from "../types"
import React from "react"
import {isEmpty} from "lodash"
import {DatepickerEditor, DatepickerEditorProps} from "./DatepickerEditor"
import {FormatterType, spelFormatters, typeFormatters} from "../Formatter"
import moment from "moment"
const dateForma... |
DateEditor.switchableToHint = () => i18next.t("editors.LocalDate.switchableToHint", "Switch to basic mode")
DateEditor.notSwitchableToHint = () => i18next.t("editors.LocalDate.notSwitchableToHint", "Expression must be valid date to switch to basic mode")
DateEditor.switchableTo = (expressionObj: ExpressionObj) => isP... | {
const {formatter} = props
const dateFormatter = formatter == null ? typeFormatters[FormatterType.Date] : formatter
return (
<DatepickerEditor
{...props}
momentFormat={dateFormat}
dateFormat={dateFormat}
timeFormat={null}
formatter={dateFormatter}
/>
)
} | identifier_body |
DateEditor.tsx | import i18next from "i18next"
import {ExpressionObj} from "../types"
import React from "react"
import {isEmpty} from "lodash"
import {DatepickerEditor, DatepickerEditorProps} from "./DatepickerEditor"
import {FormatterType, spelFormatters, typeFormatters} from "../Formatter"
import moment from "moment"
const dateForma... |
return (
<DatepickerEditor
{...props}
momentFormat={dateFormat}
dateFormat={dateFormat}
timeFormat={null}
formatter={dateFormatter}
/>
)
}
DateEditor.switchableToHint = () => i18next.t("editors.LocalDate.switchableToHint", "Switch to basic mode")
DateEditor.notSwitchableToHin... |
export function DateEditor(props: Omit<DatepickerEditorProps, "dateFormat" | "expressionType">) {
const {formatter} = props
const dateFormatter = formatter == null ? typeFormatters[FormatterType.Date] : formatter | random_line_split |
DateEditor.tsx | import i18next from "i18next"
import {ExpressionObj} from "../types"
import React from "react"
import {isEmpty} from "lodash"
import {DatepickerEditor, DatepickerEditorProps} from "./DatepickerEditor"
import {FormatterType, spelFormatters, typeFormatters} from "../Formatter"
import moment from "moment"
const dateForma... | (props: Omit<DatepickerEditorProps, "dateFormat" | "expressionType">) {
const {formatter} = props
const dateFormatter = formatter == null ? typeFormatters[FormatterType.Date] : formatter
return (
<DatepickerEditor
{...props}
momentFormat={dateFormat}
dateFormat={dateFormat}
timeForma... | DateEditor | identifier_name |
api.py | import eventlet
import gettext
import sys
from staccato.common import config
import staccato.openstack.common.wsgi as os_wsgi
import staccato.openstack.common.pastedeploy as os_pastedeploy
# Monkey patch socket and time
eventlet.patcher.monkey_patch(all=False, socket=True, time=True)
gettext.install('staccato', unic... | (returncode, e):
sys.stderr.write("ERROR: %s\n" % e)
sys.exit(returncode)
def main():
try:
conf = config.get_config_object()
paste_file = conf.find_file(conf.paste_deploy.config_file)
wsgi_app = os_pastedeploy.paste_deploy_app(paste_file,
... | fail | identifier_name |
api.py | import eventlet
import gettext
import sys
from staccato.common import config
import staccato.openstack.common.wsgi as os_wsgi
import staccato.openstack.common.pastedeploy as os_pastedeploy
# Monkey patch socket and time
eventlet.patcher.monkey_patch(all=False, socket=True, time=True)
gettext.install('staccato', unic... |
def main():
try:
conf = config.get_config_object()
paste_file = conf.find_file(conf.paste_deploy.config_file)
wsgi_app = os_pastedeploy.paste_deploy_app(paste_file,
'staccato-api',
conf)
... | sys.stderr.write("ERROR: %s\n" % e)
sys.exit(returncode) | identifier_body |
core.js | 'use strict';
/*!
* Collection
* https://github.com/kobezzza/Collection
*
* Released under the MIT license
* https://github.com/kobezzza/Collection/blob/master/LICENSE
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Collection = Collection;
exports.P = P;
exports.default = $C;
var _g... | };
},
throw(err) {
throw err;
},
return: v => {
done = true;
value = v;
}
};
} else {
this.data = (0, _types.isObjectInstance)(obj) ? (0, _gcc.any)(obj) : [];
}
}
/**
* @private
* @return {!Object}
*/
Collection.prototype._init = function ... | value | random_line_split |
core.js | 'use strict';
/*!
* Collection
* https://github.com/kobezzza/Collection
*
* Released under the MIT license
* https://github.com/kobezzza/Collection/blob/master/LICENSE
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Collection = Collection;
exports.P = P;
exports.default = $C;
var _g... | (obj) {
return new Collection(obj);
} | $C | identifier_name |
core.js | 'use strict';
/*!
* Collection
* https://github.com/kobezzza/Collection
*
* Released under the MIT license
* https://github.com/kobezzza/Collection/blob/master/LICENSE
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Collection = Collection;
exports.P = P;
exports.default = $C;
var _g... | ,
return: v => {
done = true;
value = v;
}
};
} else {
this.data = (0, _types.isObjectInstance)(obj) ? (0, _gcc.any)(obj) : [];
}
}
/**
* @private
* @return {!Object}
*/
Collection.prototype._init = function () {
const old = this.p;
this.p = new P();
return old;
};
/*... | {
throw err;
} | identifier_body |
Browser.js |
/* INIT */
/* init browser */
Browser.prototype.init = function(){
this.build();
}
/* build browser html */
Browser.prototype.build = function(){
this.$rowHolder = $(document.createElement('div')).addClass('row-holder');
this.$container.append(this.$rowHolder);
this.$scrollUpButton = $(document.createElement... | {
this.$container = $(container);
this.ready = false;
this.rows = [];
this.data = Global.data;
this.parser = Global.parser;
this.offline = window.location.hash == '#random' || window.location.hash == '#disney';
this.resizeTimer;
this.scrollTimer;
this.animationDuration = Global.animationDuration;
this.allowAn... | identifier_body | |
Browser.js | (container){
this.$container = $(container);
this.ready = false;
this.rows = [];
this.data = Global.data;
this.parser = Global.parser;
this.offline = window.location.hash == '#random' || window.location.hash == '#disney';
this.resizeTimer;
this.scrollTimer;
this.animationDuration = Global.animationDuration;
t... | Browser | identifier_name | |
Browser.js | -select':'none',
'-ms-user-select':'none',
'user-select':'none'
}).bind('selectstart', function(){ return false; });
}
/* init interactions */
Browser.prototype.initInteraction = function(){
/* listen to window resize*/
$(window).resize(this.resize.bind(this));
$(window).on('deviceorientation',this.resize.bi... |
this.scrollTo(newTop - topbarHeight);
}
/* listen to browser scroll, change scroll button colors */
Browser.prototype.scrollEvent = function(){
clearTimeout(this.scrollTimer);
this.scrollTimer = setTimeout(this.checkScroll.bind(this),200);
}
Browser.prototype.checkScroll = function(){
/* show/hide scroll button... | {
newTop = position.top;
} | conditional_block |
Browser.js | -select':'none',
'-ms-user-select':'none',
'user-select':'none'
}).bind('selectstart', function(){ return false; });
}
/* init interactions */
Browser.prototype.initInteraction = function(){
/* listen to window resize*/
$(window).resize(this.resize.bind(this));
$(window).on('deviceorientation',this.resize.bi... |
/* remove a row */
Browser.prototype.removeRow = function(row){
row.remove();
var position = this.rows.indexOf(row);
this.rows.splice(position,1);
}
/* DOCK ROWS */
Browser.prototype.dockRows = function(){
for(var i=0,len = this.rows.length; i<len; i++){
if (i < len - 2){
this.rows[i].dock();
} else{
... | random_line_split | |
SolParser.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
... | (
item : IteratingParserItem,
select : Cheerio
) : boolean {
const $element = select(item.elem);
const withinArticle = $element.parents('article').length === 1;
const isTags = $element.attr('itemprop') === 'keywords';
const isBreadCrumbs = $element.parents('div').hasClass('pageheader');
const withinSecti... | isParagraph | identifier_name |
SolParser.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
... | }
// Implement AbstractIteratingParser
protected getArticleContentScope() : string {
return 'main';
}
protected isLeadIn(
item : IteratingParserItem,
select : Cheerio
) : boolean {
const hasParentDescription = select(item.elem).parents('div').attr('itemprop') === 'description';
return item.name === '... | email: mail,
};
}));
} | random_line_split |
SolParser.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
... | else if (encodedMail.includes('/cdn-cgi/l/email-protection#')) {
mail = cfEmailDecode(encodedMail.replace('/cdn-cgi/l/email-protection#', ''));
}
return {
name: name === undefined ? undefined : name.replace(/\s+/g, ' '),
email: mail,
};
}));
}
}
// Implement AbstractIteratingParser... | {
mail = encodedMail.replace('mailto:', '');
} | conditional_block |
SolParser.ts | //
// LESERKRITIKK v2 (aka Reader Critics)
// Copyright (C) 2017 DB Medialab/Aller Media AS, Oslo, Norway
// https://github.com/dbmedialab/reader-critics/
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
... |
protected parseByline() : Promise <ArticleAuthor[]> {
const authors = getOpenGraphAuthors(this.select);
if (authors.length !== 0) {
return Promise.resolve(authors);
} else {
const authorWrap = this.select('div.byline').find('span.person').toArray();
return Promise.resolve(authorWrap.map(wrap => {
... | {
return Promise.resolve( 'cat');
} | identifier_body |
twig.functions.js | date, dump, parent, random,.
// Range function from http://phpjs.org/functions/range:499
// Used under an MIT License
range: function (low, high, step) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// * example 1: range ( 0, 1... | else {
return this.blocks[block];
}
},
parent: function() {
// Add a placeholder
return Twig.placeholders.parent;
},
attribute: function(object, method, params) {
if (Twig.lib.is('Object', object)) {
if (obj... | {
return Twig.logic.parse.apply(this, [this.originalBlockTokens[block], this.context]).output;
} | conditional_block |
twig.functions.js | date, dump, parent, random,.
// Range function from http://phpjs.org/functions/range:499
// Used under an MIT License
range: function (low, high, step) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// * example 1: range ( 0, 1... | var pos = i % arr.length;
return arr[pos];
},
dump: function() {
var EOL = '\n',
indentChar = ' ',
indentTimes = 0,
out = '',
args = Array.prototype.slice.call(arguments),
indent = functi... |
return matrix;
},
cycle: function(arr, i) { | random_line_split |
twig.functions.js | (type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
Twig.functions = {
// attribute, block, constant, date, dump, parent, random,.
// Range function from http://phpjs.org/functions/range:499
... | is | identifier_name | |
twig.functions.js |
Twig.functions = {
// attribute, block, constant, date, dump, parent, random,.
// Range function from http://phpjs.org/functions/range:499
// Used under an MIT License
range: function (low, high, step) {
// http://kevin.vanzonneveld.net
// + original by:... | {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
} | identifier_body | |
main.py | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import os
from subprocess import call, Popen, PIPE, STDOUT
class GtkPassWindow(Gtk.Window):
def __init__(self):
self.search_text = ''
self.search_result_text = ''
self.get_pass_path()
self.build_gui()... |
def fuzzy_find(self):
env = os.environ.copy()
fzf_bin = os.path.expanduser('~/.fzf/bin')
if fzf_bin not in env['PATH']:
env['PATH'] += '{}:{}'.format(env['PATH'], fzf_bin)
p = Popen(['fzf', '-f', self.search_text], env=env,
stdin=PIPE, stdout=PIPE, std... | pass_list_item = os.path.relpath(file_, self.pass_path)
pass_list_item = os.path.splitext(pass_list_item)[0]
self.pass_list.append(pass_list_item) | conditional_block |
main.py | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import os
from subprocess import call, Popen, PIPE, STDOUT
class GtkPassWindow(Gtk.Window):
def __init__(self):
self.search_text = ''
self.search_result_text = ''
self.get_pass_path()
self.build_gui()... | if __name__ == '__main__':
main() | random_line_split | |
main.py | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import os
from subprocess import call, Popen, PIPE, STDOUT
class GtkPassWindow(Gtk.Window):
def __init__(self):
self.search_text = ''
self.search_result_text = ''
self.get_pass_path()
self.build_gui()... | (self, widget, event):
if event.keyval == Gdk.KEY_Escape:
Gtk.main_quit()
self.search_text = self.text_entry.get_text().strip()
if self.search_text == '':
self.search_result_text = None
else:
search_result = self.fuzzy_find()
if search_resu... | on_key_release | identifier_name |
main.py | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
import os
from subprocess import call, Popen, PIPE, STDOUT
class GtkPassWindow(Gtk.Window):
def __init__(self):
self.search_text = ''
self.search_result_text = ''
self.get_pass_path()
self.build_gui()... |
def on_button_release(self, widget, event):
self.copy_to_clipboard()
def on_activate(self, event):
self.copy_to_clipboard()
def copy_to_clipboard(self):
if self.search_result_text:
p = call(['pass', '-c', self.search_result_text])
self.text_entry.set_icon_... | if event.keyval == Gdk.KEY_Escape:
Gtk.main_quit()
self.search_text = self.text_entry.get_text().strip()
if self.search_text == '':
self.search_result_text = None
else:
search_result = self.fuzzy_find()
if search_result == []:
self.... | identifier_body |
pdf2image.py | """
pdf2image is a light wrapper for the poppler-utils tools that can convert your
PDFs into Pillow images.
"""
import os
import platform
import re
import uuid
import tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buff... | page_count = last_page - first_page + 1
if thread_count > page_count:
thread_count = page_count
reminder = page_count % thread_count
current_page = first_page
processes = []
for i in range(thread_count):
thread_output_file = output_file + '_' + str(i) if thread_count > 1 else o... | # Recalculate page count based on first and last page | random_line_split |
pdf2image.py | """
pdf2image is a light wrapper for the poppler-utils tools that can convert your
PDFs into Pillow images.
"""
import os
import platform
import re
import uuid
import tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buff... |
return args
def _parse_format(fmt):
fmt = fmt.lower()
if fmt[0] == '.':
fmt = fmt[1:]
if fmt in ('jpeg', 'jpg'):
return 'jpeg', parse_buffer_to_jpeg, False
if fmt == 'png':
return 'png', parse_buffer_to_png, False
if fmt in ('tif', 'tiff'):
return 'tiff', None... | if use_cropbox:
args.append('-cropbox')
if transparent and fmt in TRANSPARENT_FILE_TYPES:
args.append('-transp')
if first_page is not None:
args.extend(['-f', str(first_page)])
if last_page is not None:
args.extend(['-l', str(last_page)])
if fmt != 'ppm':
args... | identifier_body |
pdf2image.py | """
pdf2image is a light wrapper for the poppler-utils tools that can convert your
PDFs into Pillow images.
"""
import os
import platform
import re
import uuid
import tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buff... |
if auto_temp_dir:
shutil.rmtree(output_folder)
return images
def convert_from_bytes(pdf_file, dpi=200, output_folder=None, first_page=None, last_page=None,
fmt='ppm', thread_count=1, userpw=None, use_cropbox=False, strict=False, transparent=False,
outpu... | data, err = proc.communicate()
if b'Syntax Error'in err and strict:
raise PDFSyntaxError(err.decode("utf8", "ignore"))
if output_folder is not None:
images += _load_from_output_folder(output_folder, uid, in_memory=auto_temp_dir)
else:
images += parse_buffer_... | conditional_block |
pdf2image.py | """
pdf2image is a light wrapper for the poppler-utils tools that can convert your
PDFs into Pillow images.
"""
import os
import platform
import re
import uuid
import tempfile
import shutil
from subprocess import Popen, PIPE
from PIL import Image
from .parsers import (
parse_buffer_to_ppm,
parse_buff... | (output_folder, output_file, in_memory=False):
images = []
for f in sorted(os.listdir(output_folder)):
if output_file in f:
images.append(Image.open(os.path.join(output_folder, f)))
if in_memory:
images[-1].load()
return images
| _load_from_output_folder | identifier_name |
iam.py | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | BIGQUERY_METADATA_VIEWER_ROLE = "roles/bigquery.metadataViewer"
"""When applied to a table or view, this role provides persmissions to
read metadata from the table or view.""" |
BIGQUERY_DATA_VIEWER_ROLE = "roles/bigquery.dataViewer"
"""When applied to a table or view, this role provides permissions to
read data and metadata from the table or view."""
| random_line_split |
urls.py | #
# Copyright (C) 2017 Maha Farhat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | url(r'^auth/', include('apps.tb_users.auth_urls')),
#url(r'.+', Tv.as_view(template_name='offline.html'), name="offline"),
url(r'^predict/', include('apps.predict.urls', namespace='predict')),
url(r'^pipeline/', include('apps.pipeline.urls')),
url(r'^uploads/', include('apps.uploads.urls')),
u... | path('gentb-admin/', admin.site.urls),
url(r'^models/', include('django_spaghetti.urls')),
url(r'^user/', include('apps.tb_users.urls')), | random_line_split |
urls.py | #
# Copyright (C) 2017 Maha Farhat
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distribu... | locals()['handler'+e] = Error.as_error(e)
urlpatterns.append(url('^error/%s/$' % e, Error.as_error(e))) | conditional_block | |
test_get_started.py | 0.77653139, 0.60509306,
0.60846943, 0.76187008, 0.73278992, 0.72792572,
0.47661681, 0.59456417, 0.71894598, 0.6731302,
0.74964489, 0.77247818, 0.78289747, 0.74200682,
0.78940242, 0.78508877, 0.73153419, 0.65636031,
0.78607775, 0.... | assert gstart["fc"] == [83999.25, 79015.5] | identifier_body | |
test_get_started.py | 346,
0.75602843, 0.42494845, 0.77653139, 0.60509306,
0.60846943, 0.76187008, 0.73278992, 0.72792572,
0.47661681, 0.59456417, 0.71894598, 0.6731302,
0.74964489, 0.77247818, 0.78289747, 0.74200682,
0.78940242, 0.78508877, 0.73153419... | test_countpix | identifier_name | |
test_get_started.py | 06,
0.60846943, 0.76187008, 0.73278992, 0.72792572,
0.47661681, 0.59456417, 0.71894598, 0.6731302,
0.74964489, 0.77247818, 0.78289747, 0.74200682,
0.78940242, 0.78508877, 0.73153419, 0.65636031,
0.78607775, 0.59738545, 0.72596162,... | random_line_split | ||
intrinsicck.rs | // Copyright 2012-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-MI... | if def.variants[data_idx].fields.len() == 1 {
return def.variants[data_idx].fields[0].ty(tcx, substs);
}
}
ty
}
impl<'a, 'tcx> ExprVisitor<'a, 'tcx> {
fn def_id_is_transmute(&self, def_id: DefId) -> bool {
self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
self.... | {
let (def, substs) = match ty.sty {
ty::Adt(def, substs) => (def, substs),
_ => return ty
};
if def.variants.len() == 2 && !def.repr.c() && def.repr.int.is_none() {
let data_idx;
let one = VariantIdx::new(1);
let zero = VariantIdx::new(0);
if def.variants[... | identifier_body |
intrinsicck.rs | // Copyright 2012-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-MI... | <'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>
}
struct ExprVisitor<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
tables: &'tcx ty::TypeckTables<'tcx>,
param_env: ty::ParamEnv<'tcx>,
}
/// If the type is `Option<T>`, it will return `T`, otherwise
/// the type itself. Works on most `Option`-like types.
fn... | ItemVisitor | identifier_name |
intrinsicck.rs | // Copyright 2012-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-MI... | if sk_from.same_size(sk_to) {
return;
}
// Special-case transmutting from `typeof(function)` and
// `Option<typeof(function)>` to present a clearer error.
let from = unpack_option_like(self.tcx.global_tcx(), from);
if let (&ty::FnD... | random_line_split | |
regress-137000.js | /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
/*
*
* Date: 03 June 2... | (p)
{
this.p = 1;
}
function childObject()
{
parentObject.call(this);
}
childObject.prototype = parentObject;
status = inSection(2);
var objParent = new parentObject();
actual = objParent.p;
expect = 1;
addThis();
status = inSection(3);
var objChild = new childObject();
actual = objChild.p;
expect = 1;
addThis()... | parentObject | identifier_name |
regress-137000.js | /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
/*
*
* Date: 03 June 2... | * Use same identifier as a property name, too -
*/
function BaseX(id)
{
}
function ChildX(id)
{
this.id = id;
}
ChildX.prototype=BaseX;
status = inSection(5);
c1 = new ChildX('child1');
actual = c1.id;
expect = 'child1';
addThis();
/*
* From http://bugzilla.mozilla.org/show_bug.cgi?id=150032
*
* Here the sa... | addThis();
/* | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.