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
developmentMiddleware.js
import compose from 'koa-compose'; import webpack from 'webpack'; import { devMiddleware, hotMiddleware } from 'koa-webpack-middleware'; // Need to mock these files for development, because our Pug template // will be looking for them, but they're actually all bundled up into one // file during development with webpa...
else { await next(); } }; } export function webpackMiddleware() { console.log("Development environment, starting HMR"); const devConfig = require('../../../webpack.config.client'); const compile = webpack(devConfig); return compose([ devMiddleware(compile, { noInfo: true, publicP...
{ ctx.body = "/*Mocked files for development " + "(not using separate bundle files for vendor" + " and app code in development mode or separate" + " files for styles either)*/"; }
conditional_block
utility.py
import numpy as np import tensorflow as tf def pairwise_add(u, v=None, is_batch=False): """ performs a pairwise summation between vectors (possibly the same) Parameters: ---------- u: Tensor (n, ) | (n, 1) v: Tensor (n, ) | (n, 1) [optional] is_batch: bool a flag for whether the ve...
(shape, axis): rank = len(shape) # num dim max_val = shape[axis] weights_vector = np.arange(1, max_val + 1, dtype=np.float32) weights_vector = weights_vector[::-1] # reversed weights_vector = np.exp(weights_vector) / np.sum(np.exp(weights_vector)) # softmax weights container = np.zeros(shape, ...
decaying_softmax
identifier_name
utility.py
import numpy as np import tensorflow as tf def pairwise_add(u, v=None, is_batch=False): """ performs a pairwise summation between vectors (possibly the same) Parameters: ---------- u: Tensor (n, ) | (n, 1) v: Tensor (n, ) | (n, 1) [optional] is_batch: bool a flag for whether the ve...
if v is None: v = u else: v_shape = v.get_shape().as_list() if u_shape != v_shape: raise ValueError("Shapes %s and %s do not match" % (u_shape, v_shape)) n = u_shape[0] if not is_batch else u_shape[1] column_u = tf.reshape(u, (-1, 1) if not is_batch else (-1, n, 1))...
raise ValueError("Expected at most 2D tensors, but got %dD" % len(u_shape)) if len(u_shape) > 3 and is_batch: raise ValueError("Expected at most 2D tensor batches, but got %dD" % len(u_shape))
random_line_split
utility.py
import numpy as np import tensorflow as tf def pairwise_add(u, v=None, is_batch=False): """ performs a pairwise summation between vectors (possibly the same) Parameters: ---------- u: Tensor (n, ) | (n, 1) v: Tensor (n, ) | (n, 1) [optional] is_batch: bool a flag for whether the ve...
else: row_v = tf.reshape(v, (1, -1) if not is_batch else (-1, 1, n)) V = tf.concat([row_v] * n, 0 if not is_batch else 1) return U + V def decaying_softmax(shape, axis): rank = len(shape) # num dim max_val = shape[axis] weights_vector = np.arange(1, max_val + 1, dtype=np.flo...
return U + tf.transpose(U, None if not is_batch else [0, 2, 1])
conditional_block
utility.py
import numpy as np import tensorflow as tf def pairwise_add(u, v=None, is_batch=False): """ performs a pairwise summation between vectors (possibly the same) Parameters: ---------- u: Tensor (n, ) | (n, 1) v: Tensor (n, ) | (n, 1) [optional] is_batch: bool a flag for whether the ve...
def unpack_into_tensorarray(value, axis, size=None): """ unpacks a given tensor along a given axis into a TensorArray Parameters: ---------- value: Tensor the tensor to be unpacked axis: int the axis to unpack the tensor along size: int the size of the array to be u...
rank = len(shape) # num dim max_val = shape[axis] weights_vector = np.arange(1, max_val + 1, dtype=np.float32) weights_vector = weights_vector[::-1] # reversed weights_vector = np.exp(weights_vector) / np.sum(np.exp(weights_vector)) # softmax weights container = np.zeros(shape, dtype=np.float32) ...
identifier_body
common.js
$(function(){ // 设置jQuery Ajax全局的参数 $.ajaxSetup({ type: "POST", error: function(jqXHR, textStatus, errorThrown){ switch (jqXHR.status){ case(500): alert("服务器系统内部错误"); break; case(401): alert("未登录"); ...
unction save(obj){ if($(obj).closest('form').valid()){ $.ajax({ type: 'post', url: webRoot+$(obj).closest('form').attr('action'), data: $(obj).closest('form').serialize(), dataType: 'json', success: function(data){ alert(messages[data.result]); search(); $(".panel-search").show(); } }...
*/ f
identifier_name
common.js
$(function(){ // 设置jQuery Ajax全局的参数 $.ajaxSetup({ type: "POST", error: function(jqXHR, textStatus, errorThrown){ switch (jqXHR.status){ case(500): alert("服务器系统内部错误"); break; case(401): alert("未登录"); ...
find('.title').text() + '</span>' + fa + '</li>' + header; if($(obj).parent().parent().attr('class') == 'sub-menu'){ return getHeader($(obj).parent().parent().prev(), title, '<i class="fa fa-angle-right"></i>'); } else{ return title; } } /** * 分页查询 * @param pageNo 页码 */ function page(pageNo){ var ur...
$(obj).parent().find('.title').after('<span class="selected"></span>'); } } /** * 初始化页面的头 * @param obj * @param header * @param fa * @returns {String} */ function getHeader(obj,header,fa){ var title = '<li><span>' + $(obj).
identifier_body
common.js
$(function(){ // 设置jQuery Ajax全局的参数 $.ajaxSetup({ type: "POST", error: function(jqXHR, textStatus, errorThrown){ switch (jqXHR.status){ case(500): alert("服务器系统内部错误"); break; case(401): alert("未登录"); ...
* @param obj 保存按钮(按钮需要在form表单中) */ function save(obj){ if($(obj).closest('form').valid()){ $.ajax({ type: 'post', url: webRoot+$(obj).closest('form').attr('action'), data: $(obj).closest('form').serialize(), dataType: 'json', success: function(data){ alert(messages[data.result]); search(); ...
* 保存
random_line_split
common.js
$(function(){ // 设置jQuery Ajax全局的参数 $.ajaxSetup({ type: "POST", error: function(jqXHR, textStatus, errorThrown){ switch (jqXHR.status){ case(500): alert("服务器系统内部错误"); break; case(401): alert("未登录"); ...
taType: 'html', success: function(data){ $(".panel-content").html(data); } }); } }); }); /** * 菜单跳转 * @param obj 菜单本身(A标签) * @param url 菜单访问地址 */ function menu(obj,url){ $('.page-sidebar-menu li').removeClass('active'); rootliActive(obj); $(obj).parent().addClass('active'); var header = '...
-search form').serialize(), da
conditional_block
columnReset.ts
/* * Copyright 2017 TWO SIGMA OPEN SOURCE, 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 appl...
this.checkFilter(); }; TableScope.prototype.resetColumnWidth = function(columnIndex: number) { this.columnWidth = this.columnWidth.splice(columnIndex, 1); }; };
TableScope.prototype.resetColumnSearch = function(columnIndex: number) { const column = this.table.column(columnIndex); column.search('');
random_line_split
columnReset.ts
/* * Copyright 2017 TWO SIGMA OPEN SOURCE, 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 appl...
(TableScope: any) { TableScope.prototype.resetColumnHeatmap = function(columnIndex: number, cellHighlighters: any) { const highlighter = this.cellHighlighters[columnIndex]; if (highlighter && highlighter instanceof cellHighlighters.HeatmapHighlighter) { this.showHideHeatmap(columnIndex); } }; ...
extendTableScopeWithColumnReset
identifier_name
columnReset.ts
/* * Copyright 2017 TWO SIGMA OPEN SOURCE, 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 appl...
}; TableScope.prototype.resetColumnDataBars = function(columnIndex: number) { this.barsOnColumn.hasOwnProperty(columnIndex) && this.showHideBars(columnIndex); }; TableScope.prototype.resetColumnColorByUnique = function(columnIndex: number) { this.haColumnUniqueEntriesHighlighted(columnIndex) && this....
{ this.showHideHeatmap(columnIndex); }
conditional_block
columnReset.ts
/* * Copyright 2017 TWO SIGMA OPEN SOURCE, 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 appl...
if (menuHelper.isFixedRight(columnIndex)) { this.pagination.fixRight = 0; } if (menuHelper.isFixedLeft(columnIndex)) { this.pagination.fixLeft = 0; } this.updateFixedColumnsSeparator(); }; TableScope.prototype.resetColumnTypesAndAlignments = function(columnIndex: number) { cons...
{ TableScope.prototype.resetColumnHeatmap = function(columnIndex: number, cellHighlighters: any) { const highlighter = this.cellHighlighters[columnIndex]; if (highlighter && highlighter instanceof cellHighlighters.HeatmapHighlighter) { this.showHideHeatmap(columnIndex); } }; TableScope.prototy...
identifier_body
level-in.js
var cmdr = require('commander') var version = require('../package.json').version var levelup = require('levelup') var args = process.argv if (args.length <= 2) { args.push('-h') } cmdr .version(version) .usage('<databaseName> [options]') .option('-d, --data [value]', 'specify data') .option('-k, --key [valu...
}
}) } } else { console.error(new Error('you need to specify a mode (put or del)'))
random_line_split
level-in.js
var cmdr = require('commander') var version = require('../package.json').version var levelup = require('levelup') var args = process.argv if (args.length <= 2) { args.push('-h') } cmdr .version(version) .usage('<databaseName> [options]') .option('-d, --data [value]', 'specify data') .option('-k, --key [valu...
else if (cmdr.mode === 'del') { if (!cmdr.key || (typeof (cmdr.key) === 'boolean')) { console.error(new Error('you need to specify a key')) } else { levelup(cmdr.args[0], {}, function (err, db) { if (err) { throw new Error('Ooooh Noooo!') } else { db.del(cmdr.key, function (err)...
{ if (!cmdr.key || (typeof (cmdr.key) === 'boolean')) { console.error(new Error('you need to specify a key')) } else if (!cmdr.value || (typeof (cmdr.value) === 'boolean')) { console.error(new Error('you need to specify a value')) } else { var db = levelup(cmdr.args[0], {}) db.put(cmdr.key, cmdr.v...
conditional_block
apply.js
// ***************************************************************************** // Copyright 2013-2019 Aerospike, Inc. // // 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...
client.apply(key, udf, policy, function (error, result) { if (error) throw error expect(result).to.eql([1, 2, 3]) done() }) }) it('should return an error if the user-defined function does not exist', function (done) { const udfArgs = { module: 'udf', funcname: 'not-such-function' } ...
args: [[1, 2, 3]] }
random_line_split
metadata.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 3 ...
def get_tagname(element): """get tagname without namespace""" try: tagname = element.tag.split('}')[1] except IndexError: tagname = element.tag return tagname
""" Attempt to parse date into datetime.datetime object Possible inputs: '20001122' '2000-11-22' '2000-11-22T11:11:11Z' '2000-11-22T' """ dateformats = ('%Y%m%d', '%Y-%m-%d', '%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT', '%Y/%m/%d') for dfmt in dateformats: try: ...
identifier_body
metadata.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 3 ...
(exml): """generate dict of properties from FGDC metadata""" vals = {} regions = [] keywords = [] mdata = Metadata(exml) identifier = mdata.idinfo.datasetid if hasattr(mdata.idinfo, 'citation'): if hasattr(mdata.idinfo.citation, 'citeinfo'): vals['spatial_representation...
fgdc2dict
identifier_name
metadata.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 3 ...
if hasattr(mdata.idinfo, 'keywords'): if mdata.idinfo.keywords.theme: for theme in mdata.idinfo.keywords.theme: if theme['themekt'] is not None: lowered_themekt = theme['themekt'].lower() # Owslib doesn't support extracting the Topic Cat...
vals['abstract'] = mdata.idinfo.descript.abstract vals['purpose'] = mdata.idinfo.descript.purpose if mdata.idinfo.descript.supplinf is not None: vals['supplemental_information'] = mdata.idinfo.descript.supplinf
conditional_block
metadata.py
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 3 ...
vals['topic_category'] = mdata.identification.topiccategory[0] if (hasattr(mdata.identification, 'keywords') and len(mdata.identification.keywords) > 0): for kw in mdata.identification.keywords: if kw['type'] == "place": regions.extend...
if len(mdata.identification.topiccategory) > 0:
random_line_split
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if !sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); ...
loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash2(n + i, &mut sieve); if opt.contains(&search)...
let mut found = 0; let mut sieve = HashMap::new();
random_line_split
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if !sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); ...
fn part1() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { ...
{ if !sieve.contains_key(&n) { let mut cur = String::from(INPUT); cur += &n.to_string(); for _ in 0..2017 { let mut hasher = Md5::new(); hasher.input_str(&cur); cur = String::from(hasher.result_str()); } sieve.insert(n, cur); } ret...
identifier_body
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if !sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); ...
() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { l...
part2
identifier_name
normalize.py
import numpy as np def zero_mean_normalize_image_data(data, axis=(0, 1, 2)): return np.divide(data - data.mean(axis=axis), data.std(axis=axis)) def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5): data = np.copy(data) if data.ndim == channel_dim or data...
return normalized_data def radiology_style_windowing(data, l, w, floor=0, ceiling=1): upper = l + w/2 lower = l - w/2 return window_data(data, floor_threshold=lower, ceiling_threshold=upper, floor=floor, ceiling=ceiling) def window_data(data, floor_threshold, ceiling_threshold, floor, ceiling): ...
normalized_data[..., i] = radiology_style_windowing(data, l, w, floor=floor, ceiling=ceiling)
conditional_block
normalize.py
import numpy as np def zero_mean_normalize_image_data(data, axis=(0, 1, 2)): return np.divide(data - data.mean(axis=axis), data.std(axis=axis)) def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5): data = np.copy(data) if data.ndim == channel_dim or data...
(data, axis=(0, 1, 2), ceiling_percentile=99, floor_percentile=1, floor=0, ceiling=1, channels_axis=None): """ :param data: Numpy ndarray. :param axis: :param ceiling_percentile: Percentile value of the foreground to set to the ceiling. :param floor_percentile: Percentile value ...
zero_one_window
identifier_name
normalize.py
import numpy as np def zero_mean_normalize_image_data(data, axis=(0, 1, 2)): return np.divide(data - data.mean(axis=axis), data.std(axis=axis)) def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5): data = np.copy(data) if data.ndim == channel_dim or data...
def window_data(data, floor_threshold, ceiling_threshold, floor, ceiling): data = (data - floor_threshold) / (ceiling_threshold - floor_threshold) # set the data below the floor to equal the floor data[data < floor] = floor # set the data above the ceiling to equal the ceiling data[data > ceiling...
upper = l + w/2 lower = l - w/2 return window_data(data, floor_threshold=lower, ceiling_threshold=upper, floor=floor, ceiling=ceiling)
identifier_body
normalize.py
import numpy as np def zero_mean_normalize_image_data(data, axis=(0, 1, 2)): return np.divide(data - data.mean(axis=axis), data.std(axis=axis)) def foreground_zero_mean_normalize_image_data(data, channel_dim=4, background_value=0, tolerance=1e-5): data = np.copy(data) if data.ndim == channel_dim or data...
channels_axis = i return channels_axis def static_windows(data, windows, floor=0, ceiling=1): """ Normalizes the data according to a set of predefined windows. This is helpful for CT normalization where the units are static and radiologists often have a set of windowing parameters that the...
# I don't understand the second part of this if statement # answer: it is checking ot make sure that the axis is not indexed in reverse (i.e. axis 3 might be # indexed as -1)
random_line_split
matrans.py
53:221-225 (2005) # What is tensor denoising? #Log-Euclidean tensor denoising was used to eliminate singular, negative definite, or rank-deficient tensors #------------------------------------------------------------------------------- #from IPython.core.debugger import Tracer; debug_here = Tracer() import argparse...
#------------------------------------------------------------------------------- def calculate_measures (funcs, data, odims): for i in range(len(funcs)): measure = funcs[i] odim = odims[i] data = measure(data) return data #----------------------------------------------------------------...
s = logm(v.reshape(N,N)) return np.sqrt(np.trace(np.square(s - np.trace(s)/N * np.eye(N))))
identifier_body
matrans.py
53:221-225 (2005) # What is tensor denoising? #Log-Euclidean tensor denoising was used to eliminate singular, negative definite, or rank-deficient tensors #------------------------------------------------------------------------------- #from IPython.core.debugger import Tracer; debug_here = Tracer() import argparse...
(v): return eigvalsh(v.reshape(N,N)).flatten() #------------------------------------------------------------------------------- def mymaxeigvalsh (v): return max (myeigvalsh(v)) #------------------------------------------------------------------------------- def mydeftensor (v): j = v.reshape([N,N]) s = ...
myeigvalsh
identifier_name
matrans.py
53:221-225 (2005) # What is tensor denoising? #Log-Euclidean tensor denoising was used to eliminate singular, negative definite, or rank-deficient tensors #------------------------------------------------------------------------------- #from IPython.core.debugger import Tracer; debug_here = Tracer() import argparse...
elif funcs[i] == 'trace': myfuncs[i] = mytrace odims [i] = 1 elif funcs[i] == 'deftensor': myfuncs[i] = mydeftensor odims [i] = N elif funcs[i] == 'eigvalsh': myfuncs[i] = myeigvalsh odims [i] = 3 elif funcs[...
myfuncs[i] = mydet odims [i] = 1
conditional_block
matrans.py
53:221-225 (2005) # What is tensor denoising? #Log-Euclidean tensor denoising was used to eliminate singular, negative definite, or rank-deficient tensors #------------------------------------------------------------------------------- #from IPython.core.debugger import Tracer; debug_here = Tracer() import argparse...
for i in range(len(funcs)): measure = funcs[i] odim = odims[i] data = measure(data) return data #------------------------------------------------------------------------------- def set_parser(): parser = argparse.ArgumentParser(description='Transforms a NxN matrix volume (N^2 volumes ...
return np.sqrt(np.trace(np.square(s - np.trace(s)/N * np.eye(N)))) #------------------------------------------------------------------------------- def calculate_measures (funcs, data, odims):
random_line_split
font.rs
3:expr, $t4:expr) => ( (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) ); } pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S'); pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B'); pub const KERN: u32 = ot_tag!('k', 'e', 'r', 'n'); static TEXT_SHAPING_PERFORMANCE_COUNTER: Ato...
let end_time = time::precise_time_ns(); TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize, Ordering::Relaxed); Arc::new(glyphs) }).clone(); self.shaper = shaper; result } ...
{ debug!("shape_text: Using Harfbuzz."); if shaper.is_none() { shaper = Some(Shaper::new(this)); } shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); }
conditional_block
font.rs
use webrender_api; macro_rules! ot_tag { ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => ( (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) ); } pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S'); pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B'); pub const KERN: u32 = ot_ta...
use text::shaping::ShaperMethods; use time; use unicode_script::Script;
random_line_split
font.rs
fn glyph_index(&self, codepoint: char) -> Option<GlyphId>; fn glyph_h_advance(&self, GlyphId) -> Option<FractionalPixel>; fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel; /// Can this font do basic horizontal LTR shaping without Harfbuzz? fn can_do_fast_shaping(&self) -> ...
FontGroup
identifier_name
meson_post_install.py
#!/usr/bin/env python3 import os import shutil import subprocess import sys if os.environ.get('DESTDIR'): install_root = os.environ.get('DESTDIR') + os.path.abspath(sys.argv[1]) else: install_root = sys.argv[1] if not os.environ.get('DESTDIR'): schemadir = os.path.join(install_root, 'glib-2.0', 'schemas') pr...
src = os.path.join(install_root, 'xsessions', 'gnome.desktop') dst = os.path.join(dst_dir, 'gnome.desktop') shutil.copyfile(src, dst)
random_line_split
meson_post_install.py
#!/usr/bin/env python3 import os import shutil import subprocess import sys if os.environ.get('DESTDIR'): install_root = os.environ.get('DESTDIR') + os.path.abspath(sys.argv[1]) else: install_root = sys.argv[1] if not os.environ.get('DESTDIR'): schemadir = os.path.join(install_root, 'glib-2.0', 'schemas') pr...
src = os.path.join(install_root, 'xsessions', 'gnome.desktop') dst = os.path.join(dst_dir, 'gnome.desktop') shutil.copyfile(src, dst)
os.makedirs(dst_dir)
conditional_block
GameObject.js
/*===================================================*\ * Requires \*===================================================*/ var merge = require('merge'), CharacteristicManager = require('./characteristics/CharacteristicManager'), JClass = require('jclass'), HashArray = require('hasharray'), EventDispatcher...
}, updatePhaser: function (phaser) { this.getChildren().all.forEach(function (child) { child.updatePhaser(phaser); }); this.updateSprite(phaser); }, destroy: function () { this.destroyed = true; }, forEach: function (callback, types) { var children = types ? this.getCh...
{ if (!this.sprite) this.buildSprite(phaser); if (this.sprite) this.sprite.updateWithModel(this); }
conditional_block
GameObject.js
/*===================================================*\ * Requires \*===================================================*/ var merge = require('merge'), CharacteristicManager = require('./characteristics/CharacteristicManager'), JClass = require('jclass'), HashArray = require('hasharray'), EventDispatcher...
this._dirty = value; (this._dirty && this.getParent()) ? this.getParent().setDirty(true) : ''; !this._dirty ? this.getChildren().forEach(function (child) { child.setDirty(false); }) : ''; }, getDirty: function() { // Serialize from server return this._dirty; }, /*========...
random_line_split
RequestPlaybackDialog.ts
import { Component, Inject } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { BehaviorSubject } from 'rxjs'; import { Gap, PlaybackRange } from '../client'; import { YamcsService } from '../core/...
sendRequest() { const ranges = []; const rangeCache = new Map<number, PlaybackRange>(); const tolerance = this.form.value['mergeTolerance'] * 60 * 1000; for (const gap of this.gaps) { const prev = rangeCache.get(gap.apid); if (prev && (this.toMillis(gap.start) - this.toMillis(prev.stop)...
{ this.gaps = this.data.gaps; this.yamcs.yamcsClient.getLinks(yamcs.instance!).then(links => { const linkOptions = []; for (const link of links) { if (link.type.indexOf('DassPlaybackPacketProvider') !== -1) { linkOptions.push({ id: link.name, label: link.na...
identifier_body
RequestPlaybackDialog.ts
import { Component, Inject } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { BehaviorSubject } from 'rxjs'; import { Gap, PlaybackRange } from '../client'; import { YamcsService } from '../core/...
} this.linkOptions$.next(linkOptions); if (linkOptions.length) { this.form.get('link')!.setValue(linkOptions[0].id); } }); } sendRequest() { const ranges = []; const rangeCache = new Map<number, PlaybackRange>(); const tolerance = this.form.value['mergeTolerance'] *...
{ linkOptions.push({ id: link.name, label: link.name, }); }
conditional_block
RequestPlaybackDialog.ts
import { Component, Inject } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { BehaviorSubject } from 'rxjs'; import { Gap, PlaybackRange } from '../client'; import { YamcsService } from '../core/...
{ gaps: Gap[]; linkOptions$ = new BehaviorSubject<Option[]>([]); form = new FormGroup({ mergeTolerance: new FormControl(30), link: new FormControl('', Validators.required) }); constructor( private dialogRef: MatDialogRef<RequestPlaybackDialog>, private yamcs: YamcsService, @Inject(MAT_...
RequestPlaybackDialog
identifier_name
RequestPlaybackDialog.ts
import { Component, Inject } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { BehaviorSubject } from 'rxjs'; import { Gap, PlaybackRange } from '../client'; import { YamcsService } from '../core/...
return utils.toDate(dateString).getTime(); } }
}); } private toMillis(dateString: string) {
random_line_split
tree.ts
import {Component,Input,Output,EventEmitter,ContentChild,TemplateRef} from '@angular/core'; import {TreeNode} from '../common'; import {UITreeNode} from './uitreenode'; @Component({ selector: 'p-tree', template: ` <div [ngClass]="'ui-tree ui-widget ui-widget-content ui-corner-all'" [ngStyle]="style" [c...
isSingleSelectionMode() { return this.selectionMode && this.selectionMode == 'single'; } isMultipleSelectionMode() { return this.selectionMode && this.selectionMode == 'multiple'; } }
{ return this.findIndexInSelection(node) != -1; }
identifier_body
tree.ts
import {Component,Input,Output,EventEmitter,ContentChild,TemplateRef} from '@angular/core'; import {TreeNode} from '../common'; import {UITreeNode} from './uitreenode'; @Component({ selector: 'p-tree', template: ` <div [ngClass]="'ui-tree ui-widget ui-widget-content ui-corner-all'" [ngStyle]="style" [c...
this.onNodeUnselect.emit({originalEvent: event, node: node}); } else { if(this.isSingleSelectionMode()) { this.selectionChange.emit(node); } else if(this.isMultipleSelectionMode()) { this.se...
{ this.selection.splice(index,1); this.selectionChange.emit(this.selection); }
conditional_block
tree.ts
import {Component,Input,Output,EventEmitter,ContentChild,TemplateRef} from '@angular/core'; import {TreeNode} from '../common'; import {UITreeNode} from './uitreenode'; @Component({ selector: 'p-tree', template: ` <div [ngClass]="'ui-tree ui-widget ui-widget-content ui-corner-all'" [ngStyle]="style" [c...
() { return this.selectionMode && this.selectionMode == 'single'; } isMultipleSelectionMode() { return this.selectionMode && this.selectionMode == 'multiple'; } }
isSingleSelectionMode
identifier_name
tree.ts
import {Component,Input,Output,EventEmitter,ContentChild,TemplateRef} from '@angular/core'; import {TreeNode} from '../common'; import {UITreeNode} from './uitreenode'; @Component({ selector: 'p-tree', template: ` <div [ngClass]="'ui-tree ui-widget ui-widget-content ui-corner-all'" [ngStyle]="style" [c...
} else if(this.isMultipleSelectionMode()) { for(let i = 0; i < this.selection.length; i++) { if(this.selection[i] == node) { index = i; break; } } } } ...
index = (this.selection == node) ? 0 : - 1;
random_line_split
extensionbar.js
// Copyright 2013 Selenium committers // Copyright 2013 Software Freedom Conservancy // // 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 ...
/** * Sets the message to display to the user in the extension bar. * @param {string} message The message text. * @param {string=} opt_color The message color; defaults to black. */ safaridriver.extension.bar.setUserMessage = function(message, opt_color) { var color = opt_color || 'black'; if (message.length ...
goog.provide('safaridriver.extension.bar');
random_line_split
extensionbar.js
// Copyright 2013 Selenium committers // Copyright 2013 Software Freedom Conservancy // // 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 ...
var bars = safari.extension.bars; for (var i = 0, n = bars.length; i < n; ++i) { var bar = bars[i]; var msgEl = bar.contentWindow.document.getElementById('message'); if (msgEl) { msgEl.innerText = message; msgEl.style.color = color; } } };
{ message = message.substring(0, 75) + '...'; }
conditional_block
polygon.py
#!/usr/bin/env python # # Copyright (c) 2010 Matteo Boscolo # # This file is part of PythonCAD. # # PythonCAD 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 opti...
return self.value[2]
identifier_body
polygon.py
#!/usr/bin/env python # # Copyright (c) 2010 Matteo Boscolo # # This file is part of PythonCAD. # # PythonCAD 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 opti...
import math from Interface.Preview.base import * from Kernel.GeoUtil.geolib import Vector from Kernel.GeoEntity.point import Point class QtPolygonItem(BaseQtPreviewItem): def __init__(self, command): super(QtPolygonItem, self).__init__(command) self.command=command ...
# # SegmentPreview object #
random_line_split
polygon.py
#!/usr/bin/env python # # Copyright (c) 2010 Matteo Boscolo # # This file is part of PythonCAD. # # PythonCAD 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 opti...
(self, painterPath): """ overloading of the shape method """ if self.center and self.vertex: painter.drawPolyline(self.polygonPoint) def boundingRect(self): """ overloading of the qt bounding rectangle """ if self.center a...
drawShape
identifier_name
polygon.py
#!/usr/bin/env python # # Copyright (c) 2010 Matteo Boscolo # # This file is part of PythonCAD. # # PythonCAD 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 opti...
def boundingRect(self): """ overloading of the qt bounding rectangle """ if self.center and self.vertex: return self.polygonPoint.boundingRect() return QtCore.QRectF(0,0 ,0.1,0.1) @property def center(self): return self.value[0]...
painter.drawPolyline(self.polygonPoint)
conditional_block
create_geotiffs.py
from optparse import make_option from optparse import OptionParser import logging #import os #import sys import contextlib #import hashlib import datetime from django.core.management.base import BaseCommand from django.conf import settings #from django.db.models import Q import dateutil import netCDF4 from lizard_ne...
nc = netCDF4.Dataset(settings.RADAR_NC_PATH, 'r') with contextlib.closing(nc): for time in times_list: try: path = netcdf.time_2_path(time) netcdf.mk_geotiff(nc, time, path) logger.info('Created geotiff for {}'.form...
interval = datetime.timedelta(minutes=5) time = time_from while time < time_to: time += interval times_list.append(time)
conditional_block
create_geotiffs.py
from optparse import make_option from optparse import OptionParser import logging #import os #import sys import contextlib #import hashlib import datetime from django.core.management.base import BaseCommand from django.conf import settings #from django.db.models import Q import dateutil import netCDF4 from lizard_ne...
option_list = BaseCommand.option_list + ( make_option( "--from", action="store", type="string", dest="from_", default="2011-01-07", help="Generate geotiffs starting from this datetime. " "Use a string in the format YYYY-MM-DD HH:MM " "(fuzzy subst...
class Command(BaseCommand): args = "" help = "Create a geotiff per timestep from the radar.nc file."
random_line_split
create_geotiffs.py
from optparse import make_option from optparse import OptionParser import logging #import os #import sys import contextlib #import hashlib import datetime from django.core.management.base import BaseCommand from django.conf import settings #from django.db.models import Q import dateutil import netCDF4 from lizard_ne...
(BaseCommand): args = "" help = "Create a geotiff per timestep from the radar.nc file." option_list = BaseCommand.option_list + ( make_option( "--from", action="store", type="string", dest="from_", default="2011-01-07", help="Generate geotiffs starting from this ...
Command
identifier_name
create_geotiffs.py
from optparse import make_option from optparse import OptionParser import logging #import os #import sys import contextlib #import hashlib import datetime from django.core.management.base import BaseCommand from django.conf import settings #from django.db.models import Q import dateutil import netCDF4 from lizard_ne...
logger.info('Created geotiff for {}'.format(time)) except: logger.exception( 'While creating geotiff for {}'.format(time))
parser = OptionParser(option_list=self.option_list) (options, args) = parser.parse_args() logger.warn("IGNORED from=%s", options.from_) logger.warn("IGNORED skip_existing=%s", options.skip_existing) time_from = dateutil.parser.parse('2011-01-07T00:00:00.000Z') time_to = dateutil...
identifier_body
Gruntfile.js
Famono.scope('famous/surfaces/Gruntfile', ["load-grunt-tasks","time-grunt"], function(require, define) { define(function() { /*global module:false*/
/*Generated initially from grunt-init, heavily inspired by yo webapp*/ module.exports = function(grunt) { 'use strict'; // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Project configu...
random_line_split
layer_function_generator.py
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import re import functools import warnings import string from six.moves import cStringIO from ..proto import framework_pb2 from ..framew...
_two_dollar_pattern_ = re.compile(r"\$\$([^\$]+)\$\$") _single_dollar_pattern_ = re.compile(r"\$([^\$]+)\$") _two_bang_pattern_ = re.compile(r"!!([^!]+)!!") def escape_math(text): return _two_bang_pattern_.sub( r'$$\1$$', _single_dollar_pattern_.sub(r':math:`\1`', ...
return framework_pb2.AttrType.Name(tp)
identifier_body
layer_function_generator.py
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import re import functools import warnings import string from six.moves import cStringIO from ..proto import framework_pb2 from ..framew...
op_type: The name of the operator to be created. This function takes in the operator type (sigmoid, mean , average etc) and creates the operator functionality. """ op_proto = OpProtoHolder.instance().get_op_proto(op_type) not_intermediate_outputs = \ [output for output in op_proto.o...
def generate_layer_fn(op_type): """Register the Python layer for an Operator. Args:
random_line_split
layer_function_generator.py
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import re import functools import warnings import string from six.moves import cStringIO from ..proto import framework_pb2 from ..framew...
(*args, **kwargs): """ Wrap func with deprecated warning """ warnings.simplefilter('always', DeprecationWarning) # turn off filter warnings.warn( "Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=...
func_wrapper
identifier_name
layer_function_generator.py
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import re import functools import warnings import string from six.moves import cStringIO from ..proto import framework_pb2 from ..framew...
return dtype def func(*args, **kwargs): helper = LayerHelper(op_type, **kwargs) dtype = infer_and_check_dtype(op_proto, *args, **kwargs) inputs = dict() for ipt in op_proto.inputs: name = _convert_(ipt.name) val = kwargs.pop(name, []) ...
raise ValueError( "operator {0} must input same dtype. {1} vs {2}".format( op_type, dtype, each.dtype))
conditional_block
logout_shortcut.js
/* * Copyright (c) 2014 ThoughtWorks, Inc. * * Pixelated 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. * * Pixelated i...
}); });
random_line_split
logout_shortcut.js
/* * Copyright (c) 2014 ThoughtWorks, Inc. * * Pixelated 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. * * Pixelated i...
}; this.after('initialize', function () { this.render(); }); }); });
{ var logoutShortcutHTML = templates.page.logoutShortcut(); this.$node.html(logoutShortcutHTML); }
conditional_block
test_pt_stop_calc_dockwidget.py
# coding=utf-8 """DockWidget test. .. note:: 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 of the License, or (at your option) any later version. """ __author__ = ...
(self): """Runs after each test.""" self.dockwidget = None def test_dockwidget_ok(self): """Test we can click OK.""" pass if __name__ == "__main__": suite = unittest.makeSuite(PTStopCalcDialogTest) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
tearDown
identifier_name
test_pt_stop_calc_dockwidget.py
# coding=utf-8 """DockWidget test. .. note:: 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 of the License, or (at your option) any later version. """ __author__ = ...
def test_dockwidget_ok(self): """Test we can click OK.""" pass if __name__ == "__main__": suite = unittest.makeSuite(PTStopCalcDialogTest) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
"""Runs after each test.""" self.dockwidget = None
identifier_body
test_pt_stop_calc_dockwidget.py
# coding=utf-8 """DockWidget test. .. note:: 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 of the License, or (at your option) any later version. """ __author__ = ...
pass if __name__ == "__main__": suite = unittest.makeSuite(PTStopCalcDialogTest) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
"""Test we can click OK."""
random_line_split
test_pt_stop_calc_dockwidget.py
# coding=utf-8 """DockWidget test. .. note:: 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 of the License, or (at your option) any later version. """ __author__ = ...
suite = unittest.makeSuite(PTStopCalcDialogTest) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
conditional_block
pool_unittest.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from pool import Pool def Run(x): if x == 10: raise Exception("Expected exception triggered by test.") retu...
(self): results = set() pool = Pool(3) for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]): results.add(result) if result < 30: pool.add([result + 20]) self.assertEquals(set(range(0, 10) + range(20, 30) + range(40, 50)), results)
testAdd
identifier_name
pool_unittest.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from pool import Pool def Run(x): if x == 10: raise Exception("Expected exception triggered by test.")
class PoolTest(unittest.TestCase): def testNormal(self): results = set() pool = Pool(3) for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]): results.add(result) self.assertEquals(set(range(0, 10)), results) def testException(self): results = set() pool = Pool(3) f...
return x
random_line_split
pool_unittest.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from pool import Pool def Run(x): if x == 10: raise Exception("Expected exception triggered by test.") retu...
def testAdd(self): results = set() pool = Pool(3) for result in pool.imap_unordered(Run, [[x] for x in range(0, 10)]): results.add(result) if result < 30: pool.add([result + 20]) self.assertEquals(set(range(0, 10) + range(20, 30) + range(40, 50)), results)
results = set() pool = Pool(3) for result in pool.imap_unordered(Run, [[x] for x in range(0, 12)]): # Item 10 will not appear in results due to an internal exception. results.add(result) expect = set(range(0, 12)) expect.remove(10) self.assertEquals(expect, results)
identifier_body
pool_unittest.py
#!/usr/bin/env python # Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from pool import Pool def Run(x): if x == 10: raise Exception("Expected exception triggered by test.") retu...
self.assertEquals(set(range(0, 10) + range(20, 30) + range(40, 50)), results)
pool.add([result + 20])
conditional_block
GenerateUpdateLines.py
def suffix(d): return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') def custom_strftime(format, t): return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day)) print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator." start = int(raw_input("Ente...
import datetime
random_line_split
GenerateUpdateLines.py
import datetime def suffix(d): return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') def custom_strftime(format, t):
print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator." start = int(raw_input("Enter initial day number: ")) stop = int(raw_input("Enter final day number: ")) t0 = datetime.date(2018, 3, 24) for d in range(start, stop+1): date = t0 + datetime.timedelta(d-1) print "...
return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
identifier_body
GenerateUpdateLines.py
import datetime def suffix(d): return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') def custom_strftime(format, t): return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day)) print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator." start = in...
# from datetime import datetime as dt # # def suffix(d): # return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') # # def custom_strftime(format, t): # return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day)) # # print custom_strftime('%B {S}, %Y', dt.now())
date = t0 + datetime.timedelta(d-1) print "| "+str(d)+" | "+custom_strftime("%a {S} %B", date)+" | | |"
conditional_block
GenerateUpdateLines.py
import datetime def
(d): return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') def custom_strftime(format, t): return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day)) print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator." start = int(raw_input("Enter initial ...
suffix
identifier_name
render_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util'; import {ComponentTemplate, Com...
exportAs: exportAs, }); }; } // Verify that DOM is a type of render. This is here for error checking only and has no use. export const renderer: Renderer3 = null as any as Document; export const element: RElement = null as any as HTMLElement; export const text: RText = null as any as Text;
export function createDirective({exportAs}: {exportAs?: string} = {}): DirectiveType<any> { return class Directive { static ngDirectiveDef = defineDirective({ factory: () => new Directive(), features: [PublicFeature],
random_line_split
render_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util'; import {ComponentTemplate, Com...
export function renderToHtml( template: ComponentTemplate<any>, ctx: any, providedRendererFactory?: RendererFactory3) { host = renderTemplate( containerEl, template, ctx, providedRendererFactory || testRendererFactory, host); return toHtml(containerEl); } beforeEach(resetDOM); export function renderCo...
{ requestAnimationFrame.queue = []; if (containerEl) { try { document.body.removeChild(containerEl); } catch (e) { } } containerEl = document.createElement('div'); containerEl.setAttribute('host', ''); document.body.appendChild(containerEl); host = null; // TODO: assert that the global...
identifier_body
render_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util'; import {ComponentTemplate, Com...
} export function createComponent( name: string, template: ComponentTemplate<any>): ComponentType<any> { return class Component { value: any; static ngComponentDef = defineComponent( {tag: name, factory: () => new Component, template: template, features: [PublicFeature]}); }; } export functio...
{ return stringifyElement(componentOrElement) .replace(/^<div host="">/, '') .replace(/<\/div>$/, '') .replace(' style=""', '') .replace(/<!--[\w]*-->/g, ''); }
conditional_block
render_util.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {stringifyElement} from '@angular/platform-browser/testing/src/browser_util'; import {ComponentTemplate, Com...
() { requestAnimationFrame.queue = []; if (containerEl) { try { document.body.removeChild(containerEl); } catch (e) { } } containerEl = document.createElement('div'); containerEl.setAttribute('host', ''); document.body.appendChild(containerEl); host = null; // TODO: assert that the glo...
resetDOM
identifier_name
fileloader.js
(function () { "use strict"; angular.module('greenpepper.services').factory('FileLoader', FileLoader); FileLoader.$inject = ['$http']; function FileLoader($http) { var httpConfig = {cache: false, headers: {'Cache-Control': 'no-cache'}}; function getlogsurl(repoName, specName) { ...
return $http.get(repoName + '/' + page, httpConfig); } function getindex(repoId) { return $http.get(repoId + ".index", httpConfig); } function getresults(repoId) { return $http.get(repoId + ".results", httpConfig); } function loadre...
{ page = specName + ".html"; }
conditional_block
fileloader.js
(function () { "use strict"; angular.module('greenpepper.services').factory('FileLoader', FileLoader); FileLoader.$inject = ['$http']; function FileLoader($http) { var httpConfig = {cache: false, headers: {'Cache-Control': 'no-cache'}}; function getlogsurl(repoName, specName) { ...
(repoId) { return $http.get(repoId + ".index", httpConfig); } function getresults(repoId) { return $http.get(repoId + ".results", httpConfig); } function loadreports() { return $http.get("index.json", httpConfig); } return { ...
getindex
identifier_name
fileloader.js
(function () { "use strict"; angular.module('greenpepper.services').factory('FileLoader', FileLoader); FileLoader.$inject = ['$http']; function FileLoader($http) { var httpConfig = {cache: false, headers: {'Cache-Control': 'no-cache'}}; function getlogsurl(repoName, specName) { ...
function getpage(repoName, specName) { var page = specName; if (!__endsWith(specName, ".html")) { page = specName + ".html"; } return $http.get(repoName + '/' + page, httpConfig); } function getindex(repoId) { return ...
{ return str.indexOf(suffix, str.length - suffix.length) !== -1; }
identifier_body
fileloader.js
(function () { "use strict"; angular.module('greenpepper.services').factory('FileLoader', FileLoader);
function getlogsurl(repoName, specName) { return repoName + '/' + specName + '-output.log'; } function getlog(repoName, specName) { return $http.get(getlogsurl(repoName, specName), httpConfig); } function __endsWith(str, suffix) { return str...
FileLoader.$inject = ['$http']; function FileLoader($http) { var httpConfig = {cache: false, headers: {'Cache-Control': 'no-cache'}};
random_line_split
node-image.ts
import * as sharp from 'sharp' import {BufferLike, IMetadata, ImageFormat, ImageResizeFit, DEFAULT_FORMAT} from './types' import {Image} from './image' import {IAnnotatedImageData, ImageData} from './image-data' import {instrumentation} from './instrumentation' import {SharpImage} from './sharp-image' export class No...
imageData = await this._applyEdges(imageData) imageData = await this._applyEffects(imageData) return SharpImage.from(imageData) } private async _applyAll(imagePromise: sharp.Sharp): Promise<sharp.Sharp> { let image = await imagePromise // Make sure the image is rotated according to EXIF i...
{ if ( !this._output.effects && !this._output.edges && !this._output.layers && !this._output.tone && !this._output.normalize && !this._output.sharpen && !this._output.calibrate ) { return image } let imageData = await SharpImage.toImageData(image) ima...
identifier_body
node-image.ts
import * as sharp from 'sharp' import {BufferLike, IMetadata, ImageFormat, ImageResizeFit, DEFAULT_FORMAT} from './types' import {Image} from './image' import {IAnnotatedImageData, ImageData} from './image-data' import {instrumentation} from './instrumentation' import {SharpImage} from './sharp-image' export class No...
(image: sharp.Sharp): Promise<sharp.Sharp> { if (!this._output.resize) { return image } const {width, height, fit, subselect, doNotEnlarge} = this._output.resize if (doNotEnlarge) { const {width: realWidth = 0, height: realHeight = 0} = await image.metadata() if (typeof width === 'num...
_applyResize
identifier_name
node-image.ts
import * as sharp from 'sharp' import {BufferLike, IMetadata, ImageFormat, ImageResizeFit, DEFAULT_FORMAT} from './types' import {Image} from './image' import {IAnnotatedImageData, ImageData} from './image-data' import {instrumentation} from './instrumentation' import {SharpImage} from './sharp-image' export class No...
public toMetadata(): Promise<IMetadata> { return SharpImage.toMetadata(this._image).then(metadata => { return {...this._metadata, ...metadata} }) } public toImageData(): Promise<IAnnotatedImageData> { return this._applyAll(this._image.clone()).then(SharpImage.toImageData) } public async to...
random_line_split
uber_API.py
#!/usr/bin/env python import json import dateutil.parser import datetime import numpy as np import calendar import itertools from flask import Flask, request, Response, render_template, redirect, url_for import Uber app = Flask(__name__) ''' The index page has links to the from_file API and the from_stream API. '''...
app.run(debug=True, threaded=True)
conditional_block
uber_API.py
#!/usr/bin/env python import json import dateutil.parser import datetime import numpy as np import calendar import itertools from flask import Flask, request, Response, render_template, redirect, url_for import Uber app = Flask(__name__) ''' The index page has links to the from_file API and the from_stream API. '''...
''' The from_file API. Accepts a get parameter 'data_file' that points at a data file containing the login data. ''' @app.route('/from_file', methods=['GET']) def from_file(): if request.method == 'GET': data_file = request.args.get('data_file', '') dp = Uber.DemandPredictor() f = open(dat...
return render_template('index.html', links={'from_file':url_for('from_file', data_file='uber_demand_prediction_challenge.json'), 'from_stream':url_for('from_stream')})
identifier_body
uber_API.py
#!/usr/bin/env python import json import dateutil.parser import datetime import numpy as np import calendar import itertools from flask import Flask, request, Response, render_template, redirect, url_for import Uber app = Flask(__name__) ''' The index page has links to the from_file API and the from_stream API. '''...
(): if request.method == 'GET': data_file = request.args.get('data_file', '') dp = Uber.DemandPredictor() f = open(data_file,'r') logins = json.loads(f.read()) f.close() logins_np = np.array([dateutil.parser.parse(x) for x in logins], dtype=datetime.datetime) ...
from_file
identifier_name
uber_API.py
#!/usr/bin/env python import json import dateutil.parser import datetime import numpy as np import calendar import itertools from flask import Flask, request, Response, render_template, redirect, url_for import Uber app = Flask(__name__) ''' The index page has links to the from_file API and the from_stream API. '''...
f = open(data_file,'r') logins = json.loads(f.read()) f.close() if request.headers.get('accept') == 'text/event-stream': return Response(login_stream(logins), content_type='text/event-stream') return redirect(url_for('static', filename='from_stream.html')) if __name__ == '__main__': ...
ret = {'day':day, 'hour':hour, 'forecast':forecast} yield "data: %s\n\n" % (json.dumps(ret)) data_file = 'uber_demand_prediction_challenge.json'
random_line_split
person-list.component.ts
import { Component, OnDestroy, OnInit, Self } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Subscription, combineLatest } from 'rxjs'; import { switchMap, scan } from 'rxjs/operators'; import * as moment from 'moment'; import { PullRequest, And, Like } from '../../../../../framewor...
constructor( @Self() public allors: ContextService, @Self() private filterService: AllorsFilterService, public metaService: MetaService, public factoryService: ObjectService, public refreshService: RefreshService, public navigateService: NavigateService, public deleteService: DeleteServic...
delete: Action; private subscription: Subscription;
random_line_split
person-list.component.ts
import { Component, OnDestroy, OnInit, Self } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Subscription, combineLatest } from 'rxjs'; import { switchMap, scan } from 'rxjs/operators'; import * as moment from 'moment'; import { PullRequest, And, Like } from '../../../../../framewor...
]); this.filterService.init(predicate); const sorter = new Sorter( { name: [m.Person.FirstName, m.Person.LastName], lastModifiedDate: m.Person.LastModifiedDate, } ); this.subscription = combineLatest(this.refreshService.refresh$, this.filterService.filterFields$, this....
{ const { m, pull, x } = this.metaService; const predicate = new And([ new Like({ roleType: m.Person.FirstName, parameter: 'firstName' }), new Like({ roleType: m.Person.LastName, parameter: 'lasttName' }), // new ContainedIn({ // propertyType: m.Person.GeneralCorrespondence, //...
identifier_body
person-list.component.ts
import { Component, OnDestroy, OnInit, Self } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Subscription, combineLatest } from 'rxjs'; import { switchMap, scan } from 'rxjs/operators'; import * as moment from 'moment'; import { PullRequest, And, Like } from '../../../../../framewor...
implements OnInit, OnDestroy { public title = 'People'; table: Table<Row>; delete: Action; private subscription: Subscription; constructor( @Self() public allors: ContextService, @Self() private filterService: AllorsFilterService, public metaService: MetaService, public factoryService: O...
PersonListComponent
identifier_name
person-list.component.ts
import { Component, OnDestroy, OnInit, Self } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Subscription, combineLatest } from 'rxjs'; import { switchMap, scan } from 'rxjs/operators'; import * as moment from 'moment'; import { PullRequest, And, Like } from '../../../../../framewor...
} }
{ this.subscription.unsubscribe(); }
conditional_block
wedding.py
""" A formulation in original variables of a wedding seating problem Authors: Stuart Mitchell 2010 """ import pulp try: import path except ImportError: pass try: import src.dippy as dippy from src.dippy import DipSolStatOptimal except ImportError: import coinor.dippy as di...
(prob, table, redCosts, target): """ Generate columns (tables) with negative reduced costs """ dvs = [] neg_guests = [g for g in guests if redCosts[x[(g,table)]] < 0.0] neg_guests.sort() # find all possible tables between two end points for pos1, pos2 in [...
relaxed_solver
identifier_name
wedding.py
""" A formulation in original variables of a wedding seating problem Authors: Stuart Mitchell 2010 """ import pulp try: import path except ImportError: pass try: import src.dippy as dippy from src.dippy import DipSolStatOptimal except ImportError: import coinor.dippy as di...
print happy[table].value()
print guest,
conditional_block
wedding.py
""" A formulation in original variables of a wedding seating problem Authors: Stuart Mitchell 2010 """ import pulp try: import path except ImportError: pass try: import src.dippy as dippy from src.dippy import DipSolStatOptimal except ImportError: import coinor.dippy as di...
for t in tables] #create a binary variable to model if a guest sits at a particular table x = pulp.LpVariable.dicts('possible_seatings', possible_seatings, lowBound = 0, upBound = 1, cat = pulp.LpInte...
#create the set of possible tables tables = range(max_tables) possible_seatings = [(g, t) for g in guests
random_line_split
wedding.py
""" A formulation in original variables of a wedding seating problem Authors: Stuart Mitchell 2010 """ import pulp try: import path except ImportError: pass try: import src.dippy as dippy from src.dippy import DipSolStatOptimal except ImportError: import coinor.dippy as di...
possible_table = [neg_guests[pos1]] + possible_table_inner +\ [neg_guests[pos2]] # calculate the sum of the reduced costs for each of the guests neg_cost = sum(redCosts[x[(g, table)]] for g in possible_table) table_happiness = happiness(possible_table[0], ...
""" Generate columns (tables) with negative reduced costs """ dvs = [] neg_guests = [g for g in guests if redCosts[x[(g,table)]] < 0.0] neg_guests.sort() # find all possible tables between two end points for pos1, pos2 in [(i, j) for i in range(len(neg_guests))...
identifier_body
notifications-list.component.ts
import { Component, Input, EventEmitter, SimpleChanges, OnChanges } from '@angular/core'; import { ToasterService } from 'angular2-toaster'; import { TranslateService } from 'ng2-translate'; import { Notification } from '../notification.model'; import { NotificationService } from '../notification.service'; import { Pa...
getPage(page: number) { this.currentPage = page; } }
{ this.translateService.get(data).subscribe( (value: any) => { this.translatedResponse = value; } ); return this.translatedResponse; }
identifier_body
notifications-list.component.ts
import { Component, Input, EventEmitter, SimpleChanges, OnChanges } from '@angular/core'; import { ToasterService } from 'angular2-toaster'; import { TranslateService } from 'ng2-translate'; import { Notification } from '../notification.model'; import { NotificationService } from '../notification.service'; import { Pa...
let readNotification = this.notifications.filter( function (notification) { return notification.id === notificationId; } )[0]; readNotification.read = true; // notify change to the service which notifies the toolbar this.notificati...
this.notificationService.markNotificationAsRead(notificationId) .then( (response: any) => {
random_line_split