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
gutters.py
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: <Enthought pyface code editor> #------------------------...
def sizeHint(self): return QtCore.QSize(self.digits_width(), 0) def paintEvent(self, event): """ Paint the line numbers. """ painter = QtGui.QPainter(self) painter.setFont(self.font) painter.fillRect(event.rect(), self.background_color) cw = self.paren...
nlines = max(1, self.parent().blockCount()) ndigits = max(self.min_char_width, int(math.floor(math.log10(nlines) + 1))) width = max(self.fontMetrics().width(u'0' * ndigits) + 3, self.min_width) return width
identifier_body
gutters.py
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: <Enthought pyface code editor> #------------------------...
class LineNumberWidget(GutterWidget): """ Draw line numbers. """ min_char_width = 4 def fontMetrics(self): # QWidget's fontMetrics method does not provide an up to date # font metrics, just one corresponding to the initial font return QtGui.QFontMetrics(self.font) def se...
painter.fillRect(QtCore.QRect(0, line*pixels_per_block, self.width(), 3), QtCore.Qt.red)
conditional_block
gutters.py
#------------------------------------------------------------------------------ # Copyright (c) 2010, Enthought Inc # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # # Author: Enthought Inc # Description: <Enthought pyface code editor> #------------------------...
QtCore.Qt.green) for line in self.warn_lines: painter.fillRect(QtCore.QRect(0, line*pixels_per_block, self.width(), 3), QtCore.Qt.yellow) for line in self.error_lines: painter.fillRect(QtCore.QRect(0, line*pixels_per_block...
pixels_per_block = self.height()/float(cw.blockCount()) for line in self.info_lines: painter.fillRect(QtCore.QRect(0, line*pixels_per_block, self.width(), 3),
random_line_split
use-user-saved-tracks.ts
import { useState, useEffect } from 'react'; import { useAuthToken } from '../../hooks/use-auth-token'; export function useUserSavedTracks()
clearAuthToken(); }); } }, [authToken, clearAuthToken, savedTracks]); return { savedTracks, }; }
{ const { authToken, clearAuthToken } = useAuthToken(); const [savedTracks, setSavedTracks] = useState<SpotifyApi.SavedSongs[]>([]); useEffect(() => { if (authToken && !savedTracks?.length) { fetch('/api/me/tracks') .then((res) => { res ...
identifier_body
use-user-saved-tracks.ts
import { useState, useEffect } from 'react'; import { useAuthToken } from '../../hooks/use-auth-token'; export function useUserSavedTracks() { const { authToken, clearAuthToken } = useAuthToken(); const [savedTracks, setSavedTracks] = useState<SpotifyApi.SavedSongs[]>([]); useEffect(() => { if (au...
}; }
random_line_split
use-user-saved-tracks.ts
import { useState, useEffect } from 'react'; import { useAuthToken } from '../../hooks/use-auth-token'; export function
() { const { authToken, clearAuthToken } = useAuthToken(); const [savedTracks, setSavedTracks] = useState<SpotifyApi.SavedSongs[]>([]); useEffect(() => { if (authToken && !savedTracks?.length) { fetch('/api/me/tracks') .then((res) => { res ...
useUserSavedTracks
identifier_name
use-user-saved-tracks.ts
import { useState, useEffect } from 'react'; import { useAuthToken } from '../../hooks/use-auth-token'; export function useUserSavedTracks() { const { authToken, clearAuthToken } = useAuthToken(); const [savedTracks, setSavedTracks] = useState<SpotifyApi.SavedSongs[]>([]); useEffect(() => { if (au...
}, [authToken, clearAuthToken, savedTracks]); return { savedTracks, }; }
{ fetch('/api/me/tracks') .then((res) => { res .json() .then((result: SpotifyApi.CurrentUserSavedSongs) => { console.log('result:', result); setSavedTracks(result.items...
conditional_block
FiletramCom.py
# -*- coding: utf-8 -*- from pyload.plugin.internal.SimpleCrypter import SimpleCrypter class FiletramCom(SimpleCrypter):
__name = "FiletramCom" __type = "crypter" __version = "0.03" __pattern = r'http://(?:www\.)?filetram\.com/[^/]+/.+' __config = [("use_premium" , "bool", "Use premium account if available" , True), ("use_subfolder" , "bool", "Save package to subfolder" , Tr...
identifier_body
FiletramCom.py
# -*- coding: utf-8 -*- from pyload.plugin.internal.SimpleCrypter import SimpleCrypter class
(SimpleCrypter): __name = "FiletramCom" __type = "crypter" __version = "0.03" __pattern = r'http://(?:www\.)?filetram\.com/[^/]+/.+' __config = [("use_premium" , "bool", "Use premium account if available" , True), ("use_subfolder" , "bool", "Save package to sub...
FiletramCom
identifier_name
FiletramCom.py
# -*- coding: utf-8 -*- from pyload.plugin.internal.SimpleCrypter import SimpleCrypter class FiletramCom(SimpleCrypter): __name = "FiletramCom" __type = "crypter" __version = "0.03"
__config = [("use_premium" , "bool", "Use premium account if available" , True), ("use_subfolder" , "bool", "Save package to subfolder" , True), ("subfolder_per_pack", "bool", "Create a subfolder for each package", True)] __description = """Filetram.c...
__pattern = r'http://(?:www\.)?filetram\.com/[^/]+/.+'
random_line_split
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
use std::rc::Rc; use syntax::ext::base::ExtCtxt; use builder::{Builder, TokenString, add_node_dependency}; use node; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutat...
random_line_split
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
if !node.expect_attributes(cx, &[("pin", node::RefAttribute), ("timer", node::RefAttribute)]) { return } let pin_node_name = node.get_ref_attr("pin").unwrap(); let timer_node_name = node.get_ref_attr("timer").unwrap(); let pin = TokenString(pin_node_name); let timer = TokenString(timer_node_na...
{return}
conditional_block
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(build_dht22 as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); node.mutator.set(Some(mutate_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let pin_node_name = node.get_ref_attr("pin").unwrap(); let pin_node ...
attach
identifier_name
dht22_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
assert_that(pin_node.get_string_attr("direction").unwrap(), is(equal_to("out".to_string()))); }); } }
{ with_parsed(" timer@timer; pin@pin; dht@dht22 { pin = &pin; timer = &timer; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); pt.get_by_name("timer").unwrap().set_type_name("T".to_string()); pt.get_by_name("pin").unwrap().set_type_name...
identifier_body
unix.rs
use syscall::arch::{syscall0, syscall1, syscall2, syscall3}; use error::Result; pub const SYS_BRK: usize = 45; pub const SYS_CHDIR: usize = 12; pub const SYS_CLONE: usize = 120; pub const CLONE_VM: usize = 0x100; pub const CLONE_FS: usize = 0x200; pub const CLONE_FILES: usize = 0x400; pub const CLONE_V...
syscall2(SYS_EXECVE, path as usize, args as usize) } pub fn sys_exit(status: usize) -> Result<usize> { unsafe { syscall1(SYS_EXIT, status) } } pub fn sys_fpath(fd: usize, buf: &mut [u8]) -> Result<usize> { unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } } pub fn sys_fstat(fd: usi...
pub unsafe fn sys_execve(path: *const u8, args: *const *const u8) -> Result<usize> {
random_line_split
unix.rs
use syscall::arch::{syscall0, syscall1, syscall2, syscall3}; use error::Result; pub const SYS_BRK: usize = 45; pub const SYS_CHDIR: usize = 12; pub const SYS_CLONE: usize = 120; pub const CLONE_VM: usize = 0x100; pub const CLONE_FS: usize = 0x200; pub const CLONE_FILES: usize = 0x400; pub const CLONE_V...
(path: *const u8) -> Result<usize> { syscall1(SYS_UNLINK, path as usize) } pub fn sys_waitpid(pid: usize, status: &mut usize, options: usize) -> Result<usize> { unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options) } } pub fn sys_write(fd: usize, buf: &[u8]) -> Result<usize> { unsafe...
sys_unlink
identifier_name
index.js
var winston = require('winston'); winston.loggers.add('http_access',{ file: { filename: process.cwd()+'/logs/http_access.log' } }); winston.loggers.add('newUsers',{ file: { filename: process.cwd()+'/logs/newUsers.log' } }); winston.loggers.add('notifies',{ file: { filename: process.cwd()+'/...
};
random_line_split
vis.py
# Copyright 2021 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, ...
mask = ~jnp.isnan(depth) x, y = jnp.meshgrid( jnp.arange(depth.shape[1]), jnp.arange(depth.shape[0]), indexing='xy') xy_var = (jnp.var(x[mask]) + jnp.var(y[mask])) / 2 z_var = jnp.var(depth[mask]) scaling = jnp.sqrt(xy_var / z_var) scaled_depth = scaling * depth normals = depth_to_norma...
def visualize_normals(depth, acc, scaling=None): """Visualize fake normals of `depth` (optionally scaled to be isotropic).""" if scaling is None:
random_line_split
vis.py
# Copyright 2021 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, ...
(depth): """Assuming `depth` is orthographic, linearize it to a set of normals.""" f_blur = jnp.array([1, 2, 1]) / 4 f_edge = jnp.array([-1, 0, 1]) / 2 dy = convolve2d(depth, f_blur[None, :] * f_edge[:, None]) dx = convolve2d(depth, f_blur[:, None] * f_edge[None, :]) inv_denom = 1 / jnp.sqrt(1 + dx**2 + dy*...
depth_to_normals
identifier_name
vis.py
# Copyright 2021 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, ...
"""A wrapper around other visualizations for easy integration.""" vis = { 'depth': visualize_depth(depth, acc), 'depth_mod': visualize_depth(depth, acc, modulus=0.1), 'depth_normals': visualize_normals(depth, acc) } return vis
identifier_body
vis.py
# Copyright 2021 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, ...
else: # Scale to [0, 1]. value = jnp.nan_to_num( jnp.clip((depth - jnp.minimum(near, far)) / jnp.abs(far - near), 0, 1)) colormap = colormap or cm.get_cmap('turbo') vis = colormap(value)[:, :, :3] # Set non-accumulated pixels to white. vis = vis * acc[:, :, None] + (1 - acc)[:, :, None] ...
value = jnp.mod(depth, modulus) / modulus colormap = colormap or sinebow
conditional_block
target_list.py
''' Copyright (C) 2014 Travis DeWolf 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 of the License, or (at your option) any later version. This program is distributed in the hope t...
def set_target(self): """ Set the current target for the controller. """ if self.target_index == len(self.target_list)-1: target = [1, 2] else: target = self.target_list[self.target_index] if target[0] != target[0]: # if it's NANs ...
"""Move to a series of targets. """ if self.controller.check_distance(arm) < self.threshold: if self.target_index < len(self.target_list)-1: self.target_index += 1 self.set_target() self.controller.apply_noise = True self.not_at_start = n...
identifier_body
target_list.py
''' Copyright (C) 2014 Travis DeWolf 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 of the License, or (at your option) any later version. This program is distributed in the hope t...
self.controller.target = target
conditional_block
target_list.py
''' Copyright (C) 2014 Travis DeWolf 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 of the License, or (at your option) any later version. This program is distributed in the hope t...
self.u = self.controller.control(arm) return self.u def set_target(self): """ Set the current target for the controller. """ if self.target_index == len(self.target_list)-1: target = [1, 2] else: target = self.target_list[self.target_...
random_line_split
target_list.py
''' Copyright (C) 2014 Travis DeWolf 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 of the License, or (at your option) any later version. This program is distributed in the hope t...
(object): """ """ def __init__(self, controller, target_list, threshold=.01, pen_down=False): """ control Control instance: the controller to use pen_down boolean: True if the end-effector is drawing """ self.controller = controller self.p...
Shell
identifier_name
reply_handler.py
# -*- coding:utf-8 -*- ''' Author: Bu Kun E-mail: bukun@osgeo.cn CopyRight: http://www.yunsuan.org ''' import tornado.web import tornado.escape import json from torlite.core import tools from torlite.core.base_handler import BaseHandler from torlite.model.mwiki import MWiki from torlite.model.mcatalog import MCatalog ...
def get(self, url_str=''): if url_str == '': return url_arr = url_str.split(r'/') if url_arr[0] == 'delete_reply': self.delete_by_id(url_arr[1]) elif url_arr[0] == 'get': self.get_by_id(url_arr[1]) elif url_arr[0] == 'zan': ...
self.muser = MUser() self.mreply = MReply() self.mreply2user = MReply2User() if self.get_current_user(): self.userinfo = self.muser.get_by_id(self.get_current_user()) else: self.userinfo = None
identifier_body
reply_handler.py
# -*- coding:utf-8 -*- ''' Author: Bu Kun E-mail: bukun@osgeo.cn CopyRight: http://www.yunsuan.org ''' import tornado.web import tornado.escape import json from torlite.core import tools from torlite.core.base_handler import BaseHandler from torlite.model.mwiki import MWiki from torlite.model.mcatalog import MCatalog ...
(self, url_str=''): if url_str == '': return url_arr = url_str.split(r'/') if url_arr[0] == 'delete_reply': self.delete_by_id(url_arr[1]) elif url_arr[0] == 'get': self.get_by_id(url_arr[1]) elif url_arr[0] == 'zan': self.zan(url_...
get
identifier_name
reply_handler.py
# -*- coding:utf-8 -*- ''' Author: Bu Kun E-mail: bukun@osgeo.cn CopyRight: http://www.yunsuan.org ''' import tornado.web import tornado.escape import json from torlite.core import tools from torlite.core.base_handler import BaseHandler from torlite.model.mwiki import MWiki from torlite.model.mcatalog import MCatalog ...
username=reply.user_name, date=reply.date, vote=reply.vote, uid=reply.uid, userinfo=self.userinfo, ) # @tornado.web.authenticated # def add_one(self, id_reply): # # post_data = {...
random_line_split
reply_handler.py
# -*- coding:utf-8 -*- ''' Author: Bu Kun E-mail: bukun@osgeo.cn CopyRight: http://www.yunsuan.org ''' import tornado.web import tornado.escape import json from torlite.core import tools from torlite.core.base_handler import BaseHandler from torlite.model.mwiki import MWiki from torlite.model.mcatalog import MCatalog ...
else: self.userinfo = None def get(self, url_str=''): if url_str == '': return url_arr = url_str.split(r'/') if url_arr[0] == 'delete_reply': self.delete_by_id(url_arr[1]) elif url_arr[0] == 'get': self.get_by_id(url_arr[1]...
self.userinfo = self.muser.get_by_id(self.get_current_user())
conditional_block
run04_model_inference.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' import time import shutil import os import matplotlib.pyplot as plt import skimage.io as skio import numpy as np import keras from keras.utils import np_utils from keras.utils.vis_utils import plot_model def readDataMasked(pidx): with open(pidx, 'r') as...
arrAcc = np.array(arrAcc) valY = valY.reshape([valY.shape[0]] + list(valX.shape[1:3]) + [valY.shape[-1]]) retY = retY.reshape([retY.shape[0]] + list(valX.shape[1:3]) + [retY.shape[-1]]) idxSorted = np.argsort(arrAcc[:,1]) plt.subplot(1,2,1) plt.plot(sorted(arrAcc[:, 0])) plt.title('Loss: %s...
arrAcc.append(model.evaluate(valX[[ii]], valY[[ii]], verbose=False)) if (ii%20)==0: print (':: eval [%d/%d]' % (ii, numVal))
conditional_block
run04_model_inference.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' import time import shutil import os import matplotlib.pyplot as plt import skimage.io as skio import numpy as np import keras from keras.utils import np_utils from keras.utils.vis_utils import plot_model def readDataMasked(pidx):
if (ii%100)==0: print ('[%d/%d]' % (ii, numPath)) return (dataX, dataY) if __name__ == '__main__': pathModel = 'test_keras_mode_v3.h5' model = keras.models.load_model(pathModel) model.summary() # fidxTrn = '/mnt/data1T2/datasets2/z_all_in_one/Portraits_256x256/idx.t...
with open(pidx, 'r') as f: wdir = os.path.dirname(pidx) lstpath = f.read().splitlines() lstpath = [os.path.join(wdir,xx) for xx in lstpath] numPath = len(lstpath) dataX = None dataY = None for ii,pp in enumerate(lstpath): img4 = skio.imread(pp) ...
identifier_body
run04_model_inference.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' import time import shutil import os import matplotlib.pyplot as plt import skimage.io as skio import numpy as np import keras from keras.utils import np_utils from keras.utils.vis_utils import plot_model def readDataMasked(pidx): with open(pidx, 'r') as...
arrAcc.append(model.evaluate(valX[[ii]], valY[[ii]], verbose=False)) if (ii%20)==0: print (':: eval [%d/%d]' % (ii, numVal)) arrAcc = np.array(arrAcc) valY = valY.reshape([valY.shape[0]] + list(valX.shape[1:3]) + [valY.shape[-1]]) retY = retY.reshape([retY.shape[0]] + list(valX.s...
arrAcc = [] numVal = valX.shape[0] for ii in range(numVal):
random_line_split
run04_model_inference.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' import time import shutil import os import matplotlib.pyplot as plt import skimage.io as skio import numpy as np import keras from keras.utils import np_utils from keras.utils.vis_utils import plot_model def
(pidx): with open(pidx, 'r') as f: wdir = os.path.dirname(pidx) lstpath = f.read().splitlines() lstpath = [os.path.join(wdir,xx) for xx in lstpath] numPath = len(lstpath) dataX = None dataY = None for ii,pp in enumerate(lstpath): img4 = skio.imread...
readDataMasked
identifier_name
quaternion_relational.rs
use na::{RealField, U4}; use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions.
pub fn quat_equal<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> { crate::equal(&x.coords, &y.coords) } /// Component-wise approximate equality comparison between two quaternions. pub fn quat_equal_eps<N: RealField>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> { crate::equal_eps(&x.coords, &y...
random_line_split
quaternion_relational.rs
use na::{RealField, U4}; use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions. pub fn quat_equal<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> { crate::equal(&x.coords, &y.coords) } /// Component-wise approximate equality comparison between two quaternions. pu...
<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4> { crate::not_equal(&x.coords, &y.coords) } /// Component-wise approximate non-equality comparison between two quaternions. pub fn quat_not_equal_eps<N: RealField>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> { crate::not_equal_eps(&x.coords, &y....
quat_not_equal
identifier_name
quaternion_relational.rs
use na::{RealField, U4}; use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions. pub fn quat_equal<N: RealField>(x: &Qua<N>, y: &Qua<N>) -> TVec<bool, U4>
/// Component-wise approximate equality comparison between two quaternions. pub fn quat_equal_eps<N: RealField>(x: &Qua<N>, y: &Qua<N>, epsilon: N) -> TVec<bool, U4> { crate::equal_eps(&x.coords, &y.coords, epsilon) } /// Component-wise non-equality comparison between two quaternions. pub fn quat_not_equal<N: Re...
{ crate::equal(&x.coords, &y.coords) }
identifier_body
test_docstring_parameters.py
# TODO inspect for Cython (see sagenb.misc.sageinspect) from __future__ import print_function from nose.plugins.skip import SkipTest from nose.tools import assert_true from os import path as op import sys import inspect import warnings import imp from pkgutil import walk_packages from inspect import getsource import...
(): """Test that there are no tabs in our source files""" for importer, modname, ispkg in walk_packages(mne.__path__, prefix='mne.'): if not ispkg and modname not in _tab_ignores: # mod = importlib.import_module(modname) # not py26 compatible! __import__(modname) # because we d...
test_tabs
identifier_name
test_docstring_parameters.py
# TODO inspect for Cython (see sagenb.misc.sageinspect) from __future__ import print_function from nose.plugins.skip import SkipTest from nose.tools import assert_true from os import path as op import sys import inspect import warnings import imp from pkgutil import walk_packages from inspect import getsource import...
def check_parameters_match(func, doc=None): """Helper to check docstring, returns list of incorrect results""" incorrect = [] name_ = get_name(func) if not name_.startswith('mne.') or name_.startswith('mne.externals'): return incorrect if inspect.isdatadescriptor(func): return incorr...
'mne.channels.tests.test_montage', # demo data has a tab ]
random_line_split
test_docstring_parameters.py
# TODO inspect for Cython (see sagenb.misc.sageinspect) from __future__ import print_function from nose.plugins.skip import SkipTest from nose.tools import assert_true from os import path as op import sys import inspect import warnings import imp from pkgutil import walk_packages from inspect import getsource import...
if inspect.isdatadescriptor(func): return incorrect args = _get_args(func) # drop self if len(args) > 0 and args[0] == 'self': args = args[1:] if doc is None: with warnings.catch_warnings(record=True) as w: doc = docscrape.FunctionDoc(func) if len(w): ...
return incorrect
conditional_block
test_docstring_parameters.py
# TODO inspect for Cython (see sagenb.misc.sageinspect) from __future__ import print_function from nose.plugins.skip import SkipTest from nose.tools import assert_true from os import path as op import sys import inspect import warnings import imp from pkgutil import walk_packages from inspect import getsource import...
method = getattr(cls, method_name) incorrect += check_parameters_match(method) if hasattr(cls, '__call__'): incorrect += check_parameters_match(cls.__call__) functions = inspect.getmembers(module, inspect.isfunction) for fname, func in function...
"""Test module docsting formatting""" if docscrape is None: raise SkipTest('This must be run from the mne-python source directory') incorrect = [] for name in public_modules: module = __import__(name, globals()) for submod in name.split('.')[1:]: module = getattr(module, ...
identifier_body
test.py
global_var = 2.11 print('main():') print('global_var = ', ++global_var) def func_use_global(): print('func_use_global():') print('global_var = ', global_var) func_use_global() def func_modify_global(): global global_var # Must declare when to reassign global variables !!!! global_var += 1 print('func_modify_gl...
# # Reassign a dictionary = modify pointer = need declare "global" # def func_modify_global_dict_2(): global global_dict global_dict = {0:88, 1:99} func_modify_global_dict_2() print('global_dict = ', global_dict)
random_line_split
test.py
global_var = 2.11 print('main():') print('global_var = ', ++global_var) def
(): print('func_use_global():') print('global_var = ', global_var) func_use_global() def func_modify_global(): global global_var # Must declare when to reassign global variables !!!! global_var += 1 print('func_modify_global():') print('global_var = ', ++global_var) func_modify_global() print('main():') print...
func_use_global
identifier_name
test.py
global_var = 2.11 print('main():') print('global_var = ', ++global_var) def func_use_global(): print('func_use_global():') print('global_var = ', global_var) func_use_global() def func_modify_global(): global global_var # Must declare when to reassign global variables !!!! global_var += 1 print('func_modify_g...
func_modify_global_dict_1() print('global_dict = ', global_dict) # # Reassign a dictionary = modify pointer = need declare "global" # def func_modify_global_dict_2(): global global_dict global_dict = {0:88, 1:99} func_modify_global_dict_2() print('global_dict = ', global_dict)
global_dict[1] = 55; global_dict[2] = 66;
identifier_body
test_indexedDB.py
from browser import window _kids=['Marsha', 'Jan', 'Cindy'] def continue1(event): _objectStore.get('Jan', onsuccess=exists, onerror=continue2) def continue2(event): for _kid in _kids: _rec={'name': _kid} _objectStore.put(_rec, _kid, onsuccess=printmsg, onerror=printerr) _objectStore.get(...
(e): print("event: ", e, "target", e.target) print("event type: ", e.type) print("e.oldVersion: ", e.oldVersion) print("e.newVersion: ", e.newVersion) # todo.. override createObjectStore to take options (ie, like OS.put) #e.target.result.createObjectStore("BradyKids") db = request.r...
onupgradeneeded
identifier_name
test_indexedDB.py
from browser import window _kids=['Marsha', 'Jan', 'Cindy'] def continue1(event): _objectStore.get('Jan', onsuccess=exists, onerror=continue2) def continue2(event):
_objectStore.put(_rec, _kid, onsuccess=printmsg, onerror=printerr) _objectStore.get('Jan', onsuccess=continue3, onerror=printerr) def continue3(event): print ("Async operations complete..") def exists(event): if event.target.pyresult() is None: #handle cause of when get returns undefined i...
for _kid in _kids: _rec={'name': _kid}
random_line_split
test_indexedDB.py
from browser import window _kids=['Marsha', 'Jan', 'Cindy'] def continue1(event): _objectStore.get('Jan', onsuccess=exists, onerror=continue2) def continue2(event): for _kid in _kids: _rec={'name': _kid} _objectStore.put(_rec, _kid, onsuccess=printmsg, onerror=printerr) _objectStore.get(...
db = None request = window.indexedDB.open("BradyKids", 3) request.onsuccess = onsuccess request.onupgradeneeded=onupgradeneeded print(db) print("allowing async operations to complete")
print(_kid, db) _rec={'name': _kid} req = db.put(_rec, _kid) req.onsuccess=printmsg req.onerror=printerr
conditional_block
test_indexedDB.py
from browser import window _kids=['Marsha', 'Jan', 'Cindy'] def continue1(event):
def continue2(event): for _kid in _kids: _rec={'name': _kid} _objectStore.put(_rec, _kid, onsuccess=printmsg, onerror=printerr) _objectStore.get('Jan', onsuccess=continue3, onerror=printerr) def continue3(event): print ("Async operations complete..") def exists(event): if event.targ...
_objectStore.get('Jan', onsuccess=exists, onerror=continue2)
identifier_body
hr-subtype.rs
// Targeted tests for the higher-ranked subtyping code. #![feature(rustc_attrs)] #![allow(dead_code)] // revisions: bound_a_vs_bound_a // revisions: bound_a_vs_bound_b // revisions: bound_inv_a_vs_bound_inv_b // revisions: bound_co_a_vs_bound_co_b // revisions: bound_a_vs_free_x // revisions: free_x_vs_free_x // revi...
//[bound_a_b_ret_a_vs_bound_a_ret_a]~^^^^ ERROR //[free_inv_x_vs_free_inv_y]~^^^^^ ERROR } }; } // If both have bound regions, they are equivalent, regardless of // variant. check! { bound_a_vs_bound_a: (for<'a> fn(&'a u32), for<'a> fn(&'a u32)) } check! { bound_a_vs_bound_b: (for<'...
//[free_x_vs_free_y]~^^ ERROR //[bound_inv_a_b_vs_bound_inv_a]~^^^ ERROR
random_line_split
hr-subtype.rs
// Targeted tests for the higher-ranked subtyping code. #![feature(rustc_attrs)] #![allow(dead_code)] // revisions: bound_a_vs_bound_a // revisions: bound_a_vs_bound_b // revisions: bound_inv_a_vs_bound_inv_b // revisions: bound_co_a_vs_bound_co_b // revisions: bound_a_vs_free_x // revisions: free_x_vs_free_x // revi...
<'a> { x: fn(&'a u32), } struct Contra<'a> { x: &'a u32, } macro_rules! check { ($rev:ident: ($t1:ty, $t2:ty)) => { #[cfg($rev)] fn subtype<'x, 'y: 'x, 'z: 'y>() { gimme::<$t2>(None::<$t1>); //[free_inv_x_vs_free_inv_y]~^ ERROR } #[cfg($rev)] ...
Co
identifier_name
netkiUtils.js
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset'...
}; function isWalletName(walletName) { var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
'fec': 'Factom Entry Credit', 'eth': 'Ethereum Ether'
random_line_split
netkiUtils.js
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset'...
(walletName) { var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
isWalletName
identifier_name
netkiUtils.js
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com'; var NETKI_API_HOST = 'https://api.netki.com'; var SHORTCODES = { 'btc': 'Bitcoin', 'tbtc': 'Bitcoin Testnet', 'ltc': 'Litecoin', 'dgc': 'Dogecoin', 'nmc': 'Namecoin', 'tusd': 'tetherUSD', 'teur': 'tetherEUR', 'tjpy': 'tetherJPY', 'oap': 'Open Asset'...
{ var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i; return pattern.test(walletName); }
identifier_body
registration_proxy.py
from registrator.models.registration_entry import RegistrationEntry from uni_info.models import Section class RegistrationProxy(RegistrationEntry):
# I guess functions for registration in Concordia's system would go here? def add_schedule_item(self, schedule_item): section_list = schedule_item.sections sections = {} sections['MainSec'] = section_list[0] for i in range(1, len(section_list)): sections['RelSec' + ...
""" Proxy class which handles actually doing the registration in a system of a :model:`registrator.RegistrationEntry` """
random_line_split
registration_proxy.py
from registrator.models.registration_entry import RegistrationEntry from uni_info.models import Section class RegistrationProxy(RegistrationEntry): """ Proxy class which handles actually doing the registration in a system of a :model:`registrator.RegistrationEntry` """ # I guess functions for reg...
class Meta: proxy = True
section_list = schedule_item.sections sections = {} sections['MainSec'] = section_list[0] for i in range(1, len(section_list)): sections['RelSec' + str(i)] = section_list[i] sections['course_letters'] = section_list[0].course.course_letters sections['course_numbers'] ...
identifier_body
registration_proxy.py
from registrator.models.registration_entry import RegistrationEntry from uni_info.models import Section class RegistrationProxy(RegistrationEntry): """ Proxy class which handles actually doing the registration in a system of a :model:`registrator.RegistrationEntry` """ # I guess functions for reg...
(self, schedule_item): section_list = schedule_item.sections sections = {} sections['MainSec'] = section_list[0] for i in range(1, len(section_list)): sections['RelSec' + str(i)] = section_list[i] sections['course_letters'] = section_list[0].course.course_letters ...
add_schedule_item
identifier_name
registration_proxy.py
from registrator.models.registration_entry import RegistrationEntry from uni_info.models import Section class RegistrationProxy(RegistrationEntry): """ Proxy class which handles actually doing the registration in a system of a :model:`registrator.RegistrationEntry` """ # I guess functions for reg...
sections['course_letters'] = section_list[0].course.course_letters sections['course_numbers'] = section_list[0].course.course_numbers sections['session'] = section_list[0].semester_year sections['CatNum'] = '12345' sections['Start'] = section_list[0].start_time sections[...
sections['RelSec' + str(i)] = section_list[i]
conditional_block
manual_verifications.py
""" Django admin commands related to verify_student """ from __future__ import absolute_import import logging import os from pprint import pformat from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from lms.djangoapps.verify_student.models import ManualVerif...
from lms.djangoapps.verify_student.utils import earliest_allowed_verification_date log = logging.getLogger(__name__) class Command(BaseCommand): """ This method attempts to manually verify users. Example usage: $ ./manage.py lms manual_verifications --email-ids-file <absolute path of file with em...
random_line_split
manual_verifications.py
""" Django admin commands related to verify_student """ from __future__ import absolute_import import logging import os from pprint import pformat from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from lms.djangoapps.verify_student.models import ManualVerif...
email_ids_file = options['email_ids_file'] if email_ids_file: if not os.path.exists(email_ids_file): raise CommandError(u'Pass the correct absolute path to email ids file as --email-ids-file argument.') total_emails, failed_emails = self._generate_manual_verificatio...
""" This method attempts to manually verify users. Example usage: $ ./manage.py lms manual_verifications --email-ids-file <absolute path of file with email ids (one per line)> """ help = 'Manually verifies one or more users passed as an argument list.' def add_arguments(self, parser): ...
identifier_body
manual_verifications.py
""" Django admin commands related to verify_student """ from __future__ import absolute_import import logging import os from pprint import pformat from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from lms.djangoapps.verify_student.models import ManualVerif...
(self, email_ids_file): """ Generate manual verification for the emails provided in the email ids file. Arguments: email_ids_file (str): path of the file containing email ids. Returns: (total_emails, failed_emails): a tuple containing count of emails processed a...
_generate_manual_verification_from_file
identifier_name
manual_verifications.py
""" Django admin commands related to verify_student """ from __future__ import absolute_import import logging import os from pprint import pformat from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from lms.djangoapps.verify_student.models import ManualVerif...
total_emails, failed_emails = self._generate_manual_verification_from_file(email_ids_file) if failed_emails: log.error(u'Completed manual verification. {} of {} failed.'.format( len(failed_emails), total_emails )) log.error(u'Failed ...
if not os.path.exists(email_ids_file): raise CommandError(u'Pass the correct absolute path to email ids file as --email-ids-file argument.')
conditional_block
game_object.js
function GameObject(x, y, w, h) { this.x = x; this.y = y; this.width = w; this.height = h; this.velX = 0; this.velY = 0; this.dead = false; } GameObject.prototype.draw = function(deltaTime) { if(this.dead) { return; } // View.ctx.fillStyle = "#FF0000"; // View.ctx.fillRect(this.x, this.y, this.width, th...
//Kill object if it's outside the world boundaries if( (this.x + this.width) < 0 || this.x > World.WIDTH || (this.y + this.height) < 0 || this.y > World.HEIGHT ) { this.dead = true; } }; function intersect(o1, o2) { return !(o1.x > o2.x + o2.width || o1.x + o1.width < o2.x || o1.y > o2.y + o2.height || o1.y...
GameObject.prototype.update = function(deltaTime) { this.x = this.x + this.velX * deltaTime; this.y = this.y + this.velY * deltaTime;
random_line_split
game_object.js
function GameObject(x, y, w, h) { this.x = x; this.y = y; this.width = w; this.height = h; this.velX = 0; this.velY = 0; this.dead = false; } GameObject.prototype.draw = function(deltaTime) { if(this.dead) { return; } // View.ctx.fillStyle = "#FF0000"; // View.ctx.fillRect(this.x, this.y, this.width, th...
; function intersect(o1, o2) { return !(o1.x > o2.x + o2.width || o1.x + o1.width < o2.x || o1.y > o2.y + o2.height || o1.y + o1.height < o2.y); }
this.dead = true; } }
conditional_block
game_object.js
function GameObject(x, y, w, h) { this.x = x; this.y = y; this.width = w; this.height = h; this.velX = 0; this.velY = 0; this.dead = false; } GameObject.prototype.draw = function(deltaTime) { if(this.dead) { return; } // View.ctx.fillStyle = "#FF0000"; // View.ctx.fillRect(this.x, this.y, this.width, th...
1, o2) { return !(o1.x > o2.x + o2.width || o1.x + o1.width < o2.x || o1.y > o2.y + o2.height || o1.y + o1.height < o2.y); }
tersect(o
identifier_name
game_object.js
function GameObject(x, y, w, h) { this.x = x; this.y = y; this.width = w; this.height = h; this.velX = 0; this.velY = 0; this.dead = false; } GameObject.prototype.draw = function(deltaTime) { if(this.dead) { return; } // View.ctx.fillStyle = "#FF0000"; // View.ctx.fillRect(this.x, this.y, this.width, th...
return !(o1.x > o2.x + o2.width || o1.x + o1.width < o2.x || o1.y > o2.y + o2.height || o1.y + o1.height < o2.y); }
identifier_body
commandline.py
from optparse import OptionParser import os,sys from oldowan.mitotype.matcher import HVRMatcher from oldowan.mitotype.prevalidate import prevalidate_submission def run_command():
dest='csv_header', default=True, help='output a csv header') parser.add_option('-o', '--out', dest='outfile', help='write results to FILE', default=False, ...
"""Perform automated human mtDNA haplotype identification.""" # Set up the options parser usage = "usage: %prog [options] sequence|filename" parser = OptionParser(usage=usage) parser.add_option('-f', '--file', action='store_true', defaul...
identifier_body
commandline.py
from optparse import OptionParser import os,sys from oldowan.mitotype.matcher import HVRMatcher from oldowan.mitotype.prevalidate import prevalidate_submission def
(): """Perform automated human mtDNA haplotype identification.""" # Set up the options parser usage = "usage: %prog [options] sequence|filename" parser = OptionParser(usage=usage) parser.add_option('-f', '--file', action='store_true', ...
run_command
identifier_name
commandline.py
from optparse import OptionParser import os,sys from oldowan.mitotype.matcher import HVRMatcher from oldowan.mitotype.prevalidate import prevalidate_submission def run_command(): """Perform automated human mtDNA haplotype identification.""" # Set up the options parser usage = "usage: %prog [options] sequ...
sys.exit(1) else: working_text = args[0] vi = prevalidate_submission(working_text) if not vi.valid: print 'ERROR: Could not validate input: %s' % vi.problem results = hvrm.match(working_text, vi) # If outfile option is used, make stdout point to that file if option...
else: print 'ERROR: Could not find file: %s' % args[0]
random_line_split
commandline.py
from optparse import OptionParser import os,sys from oldowan.mitotype.matcher import HVRMatcher from oldowan.mitotype.prevalidate import prevalidate_submission def run_command(): """Perform automated human mtDNA haplotype identification.""" # Set up the options parser usage = "usage: %prog [options] sequ...
else: print 'ERROR: Could not find file: %s' % args[0] sys.exit(1) else: working_text = args[0] vi = prevalidate_submission(working_text) if not vi.valid: print 'ERROR: Could not validate input: %s' % vi.problem results = hvrm.match(working_text, vi) ...
f = open(args[0], 'r') working_text = f.read() f.close()
conditional_block
smbios.js
'0'; } return zlp + str; } function SMBiosTables() { this._ObjectID = 'SMBiosTable'; if (process.platform == 'win32') { this._marshal = require('_GenericMarshal'); this._native = this._marshal.CreateNativeProxy("Kernel32.dll"); this._native.CreateMethod('EnumSystemFirmwareTables')...
} catch (ee) { } } i += (ret[SMtype].peek()._strings.length == 0) ? 2 : 1; ++structcount; //console.log('End of Table[' + SMtype + ']: ' + i); } //console.log('Struct Count = ' + structcount)...
{ var SMtype = SMData[i]; var SMlength = SMData[i + 1]; if (!ret[SMtype]) { ret[SMtype] = []; } ret[SMtype].push(SMData.slice(i + 4, i + SMlength)); if (process.platform == 'win32') { ret[SMtype].peek()._ext = pbyte; } i += SMlength; ...
conditional_block
smbios.js
(str, len) { if ((len == null) && (typeof (len) != 'number')) { return null; } if (str == null) str = ''; // If null, this is to generate zero leftpad string var zlp = ''; for (var i = 0; i < len - str.length; i++) { zlp += '0'; } return zlp + str; } function SMBiosTables() { this._ObjectID = '...
zeroLeftPad
identifier_name
smbios.js
function SMBiosTables() { this._ObjectID = 'SMBiosTable'; if (process.platform == 'win32') { this._marshal = require('_GenericMarshal'); this._native = this._marshal.CreateNativeProxy("Kernel32.dll"); this._native.CreateMethod('EnumSystemFirmwareTables'); this._native.CreateMe...
{ if ((len == null) && (typeof (len) != 'number')) { return null; } if (str == null) str = ''; // If null, this is to generate zero leftpad string var zlp = ''; for (var i = 0; i < len - str.length; i++) { zlp += '0'; } return zlp + str; }
identifier_body
smbios.js
'0'; } return zlp + str; } function SMBiosTables() { this._ObjectID = 'SMBiosTable'; if (process.platform == 'win32') { this._marshal = require('_GenericMarshal'); this._native = this._marshal.CreateNativeProxy("Kernel32.dll"); this._native.CreateMethod('EnumSystemFirmwareTables')...
var retVal = ms.buffer; retVal.ms = ms; return (retVal); }; } this._parse = function _parse(SMData) { var ret = {}; var pbyte; var i = 0 var SMData; var structcount = 0; while (SMData && i < SMData.length) { ...
}
random_line_split
dox.py
# Copyright (C) 2011, 2012 by Matteo Franchin # # This file is part of Pyrtist. # # Pyrtist is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 2.1 of the License, or # (at your optio...
def read_file(self, filename): """Read documentation content from the given file.""" set_log_context("File '%s'" % filename) with open(filename, "r") as f: text = f.read() slices = builder.create_classified_slices_from_text(text) blocks = builder.create_blocks_from_classified_slices(sli...
self.read_file(os.path.join(dirpath, filename))
conditional_block
dox.py
# Copyright (C) 2011, 2012 by Matteo Franchin # # This file is part of Pyrtist. # # Pyrtist is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 2.1 of the License, or # (at your optio...
(object): def __init__(self): self.file = None self.tree = DoxTree() self.context = Context() def log(self, msg, show_hdr=False): hdr = "" if show_hdr and self.file != None: hdr = self.file.filename if self.file.nr_line != None: hdr += "(%d)" % (self.file.nr_line) hdr ...
Dox
identifier_name
dox.py
# Copyright (C) 2011, 2012 by Matteo Franchin # # This file is part of Pyrtist. # # Pyrtist is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 2.1 of the License, or # (at your optio...
tree = dox.tree tree.process() from rst import RSTWriter docinfo = \ {"title": "Box Reference Manual", "has_index": True, "index_title": "Index of available object types", "out_file": "out"} writer = RSTWriter(dox.tree, docinfo=docinfo) writer.save()
dox = Dox() dox.read_recursively(sys.argv[1])
random_line_split
dox.py
# Copyright (C) 2011, 2012 by Matteo Franchin # # This file is part of Pyrtist. # # Pyrtist is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 2.1 of the License, or # (at your optio...
if doxfiles: doxfiles = list(set(doxfiles)) # Remove duplicates for filename in doxfiles: self.read_file(os.path.join(dirpath, filename)) def read_file(self, filename): """Read documentation content from the given file.""" set_log_context("File '%s'" % filename) with op...
def __init__(self): self.file = None self.tree = DoxTree() self.context = Context() def log(self, msg, show_hdr=False): hdr = "" if show_hdr and self.file != None: hdr = self.file.filename if self.file.nr_line != None: hdr += "(%d)" % (self.file.nr_line) hdr += ": " ...
identifier_body
webpack.config.js
var WebpackNotifierPlugin = require('webpack-notifier');
module.exports = { entry: "./src/index.tsx", output: { filename: "bundle.js", path: __dirname + "/dist" }, // Enable sourcemaps for debugging webpack's output. devtool: "source-map", resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts"...
random_line_split
util.py
# encoding: utf-8 # # # 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/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from __...
return output # FOR ELASTICSEARCH aggs aggregates1_4 = { "none": "none", "one": "count", "sum": "sum", "add": "sum", "count": "value_count", "maximum": "max", "minimum": "min", "max": "max", "min": "min", "mean": "avg", "average": "avg", "avg": "avg", "N": "cou...
pass
conditional_block
util.py
# encoding: utf-8 # # # 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/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from __...
"var": "variance", "variance": "variance" }
"stddev": "std_deviation",
random_line_split
util.py
# encoding: utf-8 # # # 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/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from __...
# FOR ELASTICSEARCH aggs aggregates1_4 = { "none": "none", "one": "count", "sum": "sum", "add": "sum", "count": "value_count", "maximum": "max", "minimum": "min", "max": "max", "min": "min", "mean": "avg", "average": "avg", "avg": "avg", "N": "count", "X0": "co...
output = [] for s in sort: if s.sort == 1: output.append(s.field) elif s.sort == -1: output.append({s.field: "desc"}) else: pass return output
identifier_body
util.py
# encoding: utf-8 # # # 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/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from __...
(sort): output = [] for s in sort: if s.sort == 1: output.append(s.field) elif s.sort == -1: output.append({s.field: "desc"}) else: pass return output # FOR ELASTICSEARCH aggs aggregates1_4 = { "none": "none", "one": "count", "sum": "...
qb_sort_to_es_sort
identifier_name
overlay.py
"\tExtracting layers... ", for i in range(0,len(elementsInstance['features'])): #print elementsInstance['features'][cntdel]['properties'] if str(elementsInstance['features'][cntdel]['properties'][key])!=feature: #print "del", elementsInstance['features'][cnt_featureelement] del elementsInstance['featur...
(outputFolder,inputFile,xpixel=480,ypixel=360,zoomLevel=None,lonshift=0,latshift=0, shiftformat=1,top=10,stats=None,count=None,key='Descriptio',epsg=None, elements=None,randomImages=False,sat=None): ''' Overlays images in satiImageFolder with data in inputFile ''' if not zoomLevel: print "Warning: Zoom level...
overlay
identifier_name
overlay.py
out_format='PNG', init=0, te=te, burn_values=[i]) # set image limits in te #make 0s transparent to prepare for merge img = Image.open(outFile) img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((0, 0...
outFile, ts=size, # set resolution
random_line_split
overlay.py
.split(inputFile)[-1][:-5])] else: image_files = [f for f in listImages if f.endswith('.png')] if len(image_files)==0: print "Error: No images found in",sat[0:-1] exit() else: print "Number of images found:",len(image_files) if count: print "Create",count,"images" else: print "Create",len(image_f...
pool = Pool() print 'Map to cores...' #pool only takes 1-argument functions, so create partial function partial_rasterLayer=\ partial(rasterLayer,stats=stats,subpath=subpath,size=size,te=te) pool.map(partial_rasterLayer, range(0,len(stats))) pool.close() pool.join()
conditional_block
overlay.py
img = Image.open(outFile) img = img.convert("RGBA") datas = img.getdata() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((0, 0, 0, 0)) else: newData.append(item) img.putdata(newData) img.save(outFile, "PNG") #os.remove(featureFile) def createLa...
'''converts feature geojson to png image''' feature=str(stats[i]) i+=1 print "Layer "+str(i)+"/"+str(len(stats))+'\t Processing feature: '+feature outFile=subpath+"/f_"+str(i)+".png" featureFile =subpath+"/"+featureDataFolder+"/f_"+str(i)+".json" try: os.remove(outFile) except OSError: pass gdal_rasterize....
identifier_body
tables.py
# Copyright 2014 Kylincloud # # 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 ...
policy_rules = (("network", "delete_agent"),) def delete(self, request, obj_id): network_id = self.table.kwargs['network_id'] network_info = api.neutron.network_get(request, network_id) try: api.neutron.remove_network_from_dhcp_agent(request, obj_id, ...
return ungettext_lazy( u"Deleted DHCP Agent", u"Deleted DHCP Agents", count )
identifier_body
tables.py
# Copyright 2014 Kylincloud # # 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 ...
policy_rules = (("network", "update_agent"),) def get_link_url(self, datum=None): network_id = self.table.kwargs['network_id'] return reverse(self.url, args=(network_id,)) def get_agent_status(agent): if agent.admin_state_up: return _('Enabled') return _('Disabled') def get_...
verbose_name = _("Add DHCP Agent") url = "horizon:admin:networks:adddhcpagent" classes = ("ajax-modal",) icon = "plus"
random_line_split
tables.py
# Copyright 2014 Kylincloud # # 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 ...
return _('Down') class DHCPAgentsFilterAction(tables.FilterAction): name = "agents" class DHCPAgentsTable(tables.DataTable): id = tables.Column('id', verbose_name=_('ID'), hidden=True) host = tables.Column('host', verbose_name=_('Host')) status = tables.Column(get_agent_status, verbose_name=_('...
return _('Up')
conditional_block
tables.py
# Copyright 2014 Kylincloud # # 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 ...
(agent): if agent.admin_state_up: return _('Enabled') return _('Disabled') def get_agent_state(agent): if agent.alive: return _('Up') return _('Down') class DHCPAgentsFilterAction(tables.FilterAction): name = "agents" class DHCPAgentsTable(tables.DataTable): id = tables.Col...
get_agent_status
identifier_name
python_requirement_library.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.p...
(Target): """A set of pip requirements. :API: public """ def __init__(self, payload=None, requirements=None, **kwargs): """ :param requirements: pip requirements as `python_requirement <#python_requirement>`_\s. :type requirements: List of python_requirement calls """ payload = payload or ...
PythonRequirementLibrary
identifier_name
python_requirement_library.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement) from pants.backend.python.python_requirement import PythonRequirement from pants.base.payload import Payload from pants.base.payload_field import PythonRequirementsField from pants.base.validation import assert_list from pants.build_graph.target import Target ...
random_line_split
python_requirement_library.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.p...
@property def requirements(self): return self.payload.requirements
""" :param requirements: pip requirements as `python_requirement <#python_requirement>`_\s. :type requirements: List of python_requirement calls """ payload = payload or Payload() assert_list(requirements, expected_type=PythonRequirement, key_arg='requirements') payload.add_fields({ 'requ...
identifier_body
welcome-view.js
37.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507" /> <path d="M76.7...
> Atom docs </a>{' '}
random_line_split
welcome-view.js
}); } didChangeShowOnStartup() { atom.config.set('welcome.showOnStartup', this.checked); } update() {} serialize() { return { deserializer: 'WelcomeView', uri: this.props.uri }; } render() { return ( <div className="welcome"> <div className="welcome-conta...
{ this.props.reporterProxy.sendEvent( `clicked-welcome-${link.dataset.event}-link` ); }
conditional_block
welcome-view.js
() { return { deserializer: 'WelcomeView', uri: this.props.uri }; } render() { return ( <div className="welcome"> <div className="welcome-container"> <header className="welcome-header"> <a href="https://atom.io/"> <svg classN...
serialize
identifier_name
welcome-view.js
render() { return ( <div className="welcome"> <div className="welcome-container"> <header className="welcome-header"> <a href="https://atom.io/"> <svg className="welcome-logo" width="330px" height="68px" ...
{ return { deserializer: 'WelcomeView', uri: this.props.uri }; }
identifier_body
gulpfile.js
'use strict'; var gulp = require('gulp'), fs = require("fs"), runSequence = require('run-sequence'), gulpsync = require('gulp-sync')(gulp), inline = require('inline-html'), replace = require('gulp-string-replace'), sass = require('gulp-sass'), concat = require('gulp-concat'), rename = require("gulp-rename"), ...
// Minify JS gulp.task('concat', ['html2js'] , function(done) { return gulp.src( ['./src/component.js', './src/template/template.js'] ) .pipe( concat('main.js') ) .pipe( sourcemaps.init() ) .pipe( uglify() ) .pipe( sourcemaps.write() ) .pipe( gulp.dest( './dist/js' ) ); }); // Secuence js gulp.task('js', f...
random_line_split
token.rs
)` Paren, /// A square bracket: `[` or `]` Bracket, /// A curly brace: `{` or `}` Brace, /// An empty delimiter NoDelim, } impl DelimToken { pub fn len(self) -> usize { if self == NoDelim { 0 } else { 1 } } pub fn is_empty(self) -> bool { self == NoDelim } }...
(&self) -> bool { match self.ident() { Some(id) => id.name == keywords::Super.name() || id.name == keywords::SelfValue.name() || id.name == keywords::SelfType.name(), None => false, } } /// Returns `true` if the token is ei...
is_path_segment_keyword
identifier_name
token.rs
`)` Paren, /// A square bracket: `[` or `]` Bracket, /// A curly brace: `{` or `}` Brace, /// An empty delimiter NoDelim, } impl DelimToken { pub fn len(self) -> usize { if self == NoDelim { 0 } else { 1 } } pub fn is_empty(self) -> bool { self == NoDelim }
Char(ast::Name), Integer(ast::Name), Float(ast::Name), Str_(ast::Name), StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */ ByteStr(ast::Name), ByteStrRaw(ast::Name, usize), /* raw byte str delimited by n hash symbols */ } impl Lit { pub fn short_name(&self) -> &'static ...
} #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, Copy)] pub enum Lit { Byte(ast::Name),
random_line_split
date.rs
// Copyright 2016 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law...
} fn update(&mut self, now: time::Timespec) { self.amt = 0; write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap(); self.next_update = now + Duration::seconds(1); self.next_update.nsec = 0; } } struct LocalBuffer<'a>(&'a mut LastRenderedNow); impl<'a> fmt::Write ...
impl LastRenderedNow { fn buffer(&self) -> &str { str::from_utf8(&self.bytes[..self.amt]).unwrap()
random_line_split