file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // All...
#[allow(dead_code)] fn main() { std::process::exit(uumain(std::env::args().collect())); }
{ unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent(); loop { let line = getutxent(); if line == ptr::null() { break; } if (*line).ut_type == USER_PROCESS...
identifier_body
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // All...
() { std::process::exit(uumain(std::env::args().collect())); }
main
identifier_name
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // All...
let filename = if matches.free.len() > 0 { matches.free[0].as_ref() } else { DEFAULT_FILE }; exec(filename); 0 } fn exec(filename: &str) { unsafe { utmpxname(CString::new(filename).unwrap().as_ptr()); } let mut users = vec!(); unsafe { setutxent...
{ println!("{} {}", NAME, VERSION); return 0; }
conditional_block
users.rs
#![crate_name = "users"] /* * This file is part of the uutils coreutils package. * * (c) KokaKiwi <kokakiwi@kokakiwi.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: whoami (GNU coreutils) 8.22 */ // All...
extern crate libc; #[macro_use] extern crate uucore; use getopts::Options; use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use uucore::utmpx::*; extern { fn getutxent() -> *const c_utmp; fn getutxid(ut: *const c_utmp) -> *const c_utmp; fn getutxline(ut: *const c_utmp) -> *const c_utmp; fn...
extern crate getopts;
random_line_split
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except Nam...
else: filesystem_errors = "strict" def filesystem_encode(u): return u.encode(sys.getfilesystemencoding(), filesystem_errors) # Represent escaped bytes and strings in a portable way. # # as_bytes: Allow a Python 3.x string to represent a bytes object. # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3....
filesystem_errors = "surrogateescape"
conditional_block
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except Nam...
(): try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO return BytesIO def get_StringIO(): try: from cStringIO import StringIO except ImportError: from io import StringIO return StringIO def ord_(o): try: return ...
get_BytesIO
identifier_name
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except Nam...
return u.encode(sys.getfilesystemencoding(), filesystem_errors) # Represent escaped bytes and strings in a portable way. # # as_bytes: Allow a Python 3.x string to represent a bytes object. # e.g.: as_bytes("a\x01\b") == b"a\x01b" # Python 3.x # as_bytes("a\x01\b") == "a\x01b" # Python 2.x # as_unicode:...
else: filesystem_errors = "strict" def filesystem_encode(u):
random_line_split
compat.py
"""Python 2.x/3.x compatibility tools""" import sys __all__ = ['geterror', 'long_', 'xrange_', 'ord_', 'unichr_', 'unicode_', 'raw_input_', 'as_bytes', 'as_unicode'] def geterror (): return sys.exc_info()[1] try: long_ = long except NameError: long_ = int try: xrange_ = xrange except Nam...
def as_unicode(rstring): """ r'<Unicode literal>' => '<Unicode literal>' """ return rstring.encode('ascii', 'strict').decode('unicode_escape', 'stict') # Include a next compatible function for Python versions < 2.6 try: next_ = ne...
""" '<binary literal>' => b'<binary literal>' """ return string.encode('latin-1', 'strict')
identifier_body
cmd_isready_test.rs
// Raven is a high performance UCI chess engine // Copyright (C) 2015-2015 Nam Pham // // 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) ...
() { let r = Command::parse("isready param1 param2"); assert!(r.is_err()); }
test_create_good_isready_command_but_with_extra_params
identifier_name
cmd_isready_test.rs
// Raven is a high performance UCI chess engine // Copyright (C) 2015-2015 Nam Pham // // 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) ...
#[test] fn test_create_good_isready_command_but_with_extra_params() { let r = Command::parse("isready param1 param2"); assert!(r.is_err()); }
{ let r = Command::parse("nonexistence"); assert!(r.is_err()); }
identifier_body
cmd_isready_test.rs
// Raven is a high performance UCI chess engine // Copyright (C) 2015-2015 Nam Pham //
// // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License...
// 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.
random_line_split
index.tsx
import React from 'react'; import { isEqual } from 'lodash'; import { Dispatch } from 'redux'; import { useSelector, useDispatch } from 'react-redux'; import { RouteComponentProps, withRouter } from 'react-router-dom'; import Popover from '@material-ui/core/Popover'; import { Button } from '@pluto_network/pluto-design-...
> <div className={s.filterWrapper}> <JournalFilterInput forwardedRef={inputEl} onSubmit={(journals: AggregationJournal[]) => { dispatch({ type: ACTION_TYPES.ARTICLE_SEARCH_ADD_JOURNAL_FILTER_ITEMS, payload: { journals } }); }} /> ...
elevation={0} transitionDuration={150} classes={{ paper: s.dropBoxWrapper, }}
random_line_split
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible.
fn main() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y { 2 } else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 };...
random_line_split
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn main()
{ let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y { 2 } else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let ...
identifier_body
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn
() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y { 2 } else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; l...
main
identifier_name
single-line-if-else.rs
// rustfmt-single_line_if_else_max_width: 100 // Format if-else expressions on a single line, when possible. fn main() { let a = if 1 > 2 { unreachable!() } else { 10 }; let a = if x { 1 } else if y
else { 3 }; let b = if cond() { 5 } else { // Brief comment. 10 }; let c = if cond() { statement(); 5 } else { 10 }; let d = if let Some(val) = turbo { "cool" } else { "beans" }; if cond() { statement(); } else { other...
{ 2 }
conditional_block
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version num...
"""Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.pa...
identifier_body
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version num...
elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(major + sub) def get_major_version(version=None): "Returns major version from VERSION." version = get_complete_version(version) parts = 2 if versio...
sub = '.dev%s' % git_changeset
conditional_block
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version num...
(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', '...
get_complete_version
identifier_name
version.py
from __future__ import unicode_literals import datetime import os import subprocess from django.utils.lru_cache import lru_cache def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version num...
def get_complete_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[...
random_line_split
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*...
{}
identifier_body
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*...
() {}
main
identifier_name
invalid-punct-ident-2.rs
// aux-build:invalid-punct-ident.rs // rustc-env:RUST_BACKTRACE=0 // FIXME https://github.com/rust-lang/rust/issues/59998 // normalize-stderr-test "thread.*panicked.*proc_macro_server.rs.*\n" -> "" // normalize-stderr-test "note:.*RUST_BACKTRACE=1.*\n" -> "" // normalize-stderr-test "\nerror: internal compiler error.*...
// normalize-stderr-test "end of query stack\n" -> "" #[macro_use] extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked fn main() {}
// normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" // normalize-stderr-test "query stack during panic:\n" -> "" // normalize-stderr-test "we're just showing a limited slice of the query stack\n" -> ""
random_line_split
sql-meta-provider.js
'use babel'; import utils from '../utils'; class SQLMetaProvider { constructor() { this.selector = '.source.sql, .source.pgsql'; this.disableForSelector = '.source.sql .string, .source.sql .comment' this.filterSuggestions = true; atom.config.observe( // called immediately and on update 'autoco...
} resolve(results); }); } } export default new SQLMetaProvider();
{ // Get by matched alias table results = this.getColumnNames(editor, search, tableName); }
conditional_block
sql-meta-provider.js
'use babel'; import utils from '../utils'; class SQLMetaProvider { constructor() { this.selector = '.source.sql, .source.pgsql'; this.disableForSelector = '.source.sql .string, .source.sql .comment' this.filterSuggestions = true; atom.config.observe( // called immediately and on update 'autoco...
} getColumnNames(editor, columnSearch, objectName) { let columns = editor.dataAtomColumns || []; if (columns.length == 0) return []; let valid = columns.filter((col) => { if (objectName) return col.tableName === objectName; else return true; }); return valid.m...
});
random_line_split
sql-meta-provider.js
'use babel'; import utils from '../utils'; class SQLMetaProvider { constructor() { this.selector = '.source.sql, .source.pgsql'; this.disableForSelector = '.source.sql .string, .source.sql .comment' this.filterSuggestions = true; atom.config.observe( // called immediately and on update 'autoco...
(editor, search) { let items = editor.dataAtomSchemata || []; if (items.length == 0) return []; return items.map((item) => { return { text: item.name, rightLabelHTML: `<span class="data-atom autocomplete"></span>${item.type}` }; }); } getTableNames(editor, tableSea...
getSchemaNames
identifier_name
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run...
Y.append(normalized_value) return X, Y def _fetch_test_data(self): """ 获取测试数据 """ session = get_db_session() objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '彝良县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs...
X.append(col_list) normalized_value = normalize('ny_person_income', getattr(item, 'ny_person_income'))
random_line_split
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run...
objs = session.query(Pinkunhu2015).filter(Pinkunhu2015.county == '彝良县', Pinkunhu2015.ny_person_income != -1).all() X, Y = [], [] for item in objs: col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_bac...
n X, Y def _fetch_test_data(self): """ 获取测试数据 """ session = get_db_session()
conditional_block
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run...
"" # 获取数据 X, Y = self._fetch_data() clf = self.get_classifier(X, Y) # 测试 X, Y = self._fetch_test_data() res = [] for item in range(11): hit_ratio = self.predict(clf, X, Y, item * 0.1) res.append([item * 0.1 * 100, hit_ratio * 100]) ...
行 "
identifier_name
model.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import math import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from data.dbaccess import normalize from data.db import get_db_session, Pinkunhu2015 class LassoModel(object): """ 使用Lasso预测下一年人均年收入 """ def run...
col_list = [] for col in [ 'tv', 'washing_machine', 'fridge', 'reason', 'is_danger_house', 'is_back_poor', 'is_debt', 'standard', 'arable_land', 'debt_total', 'living_space', 'member_count', 'subsidy_total', 'wood_land', 'xin_nong_he_total...
Y2 = clf.predict(X) total, hit = len(Y), 0 for idx, v in enumerate(Y2): if math.fabs(Y[idx] - v) <= math.fabs(Y[idx] * deviation): # 误差小于deviation,则认为预测准确 hit += 1 print 'Deviation: %d%%, Total: %d, Hit: %d, Precision: %.2f%%' % (100 * deviation, total, hit, 100....
identifier_body
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def loa...
with self.viewer.txn() as s: modify_state_for_body(s, body) prefetch_states = [] for i in range(self.num_to_prefetch): prefetch_index = self.index + i + 1 if prefetch_index >= len(self.bodies): break prefetch_state = copy.deepcop...
s.layers['segmentation'].segments = frozenset([body.segment_id]) s.voxel_coordinates = body.bbox_start + body.bbox_size // 2
identifier_body
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def loa...
def save(self): tmp_path = self.path + '.tmp' with open(tmp_path, 'w') as f: f.write(json.dumps(self.body_labels.items())) os.rename(tmp_path, self.path) Body = collections.namedtuple('Body', ['segment_id', 'num_voxels', 'bbox_start', 'bbox_size']) class Tool(object): d...
with open(self.path, 'r') as f: self.body_labels = collections.OrderedDict(json.load(f))
conditional_block
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def loa...
s.concurrent_downloads = 256 s.gpu_memory_limit = 2 * 1024 * 1024 * 1024 s.layout = '3d' key_bindings = [ ['bracketleft', 'prev-index'], ['bracketright', 'next-index'], ['home', 'first-index'], ['end', 'last-index'], ...
with self.viewer.txn() as s: s.layers['image'] = neuroglancer.ImageLayer(source=image_url) s.layers['segmentation'] = neuroglancer.SegmentationLayer(source=segmentation_url) s.show_slices = False
random_line_split
filter_bodies.py
from __future__ import division import json import os import copy import collections import argparse import csv import neuroglancer import neuroglancer.cli import numpy as np class State(object): def __init__(self, path): self.path = path self.body_labels = collections.OrderedDict() def loa...
(self): body_index = 0 while self.bodies[body_index].segment_id in self.state.body_labels: body_index += 1 return body_index def set_index(self, index): if index == self.index: return body = self.bodies[index] self.index = index def m...
_find_one_after_last_labeled_index
identifier_name
pressureInitial_n.py
from proteus import * from proteus.default_n import * from pressureInitial_p import * triangleOptions = triangleOptions femSpaces = {0:pbasis} stepController=FixedStep #numericalFluxType = NumericalFlux.ConstantAdvection_Diffusion_SIPG_exterior #weak boundary conditions (upwind ?) matrix = LinearAlgebraTools.Spars...
parallelPartitioningType = parallelPartitioningType nLayersOfOverlapForParallel = nLayersOfOverlapForParallel nonlinearSmoother = None linearSmoother = None numericalFluxType = NumericalFlux.ConstantAdvection_exterior linear_solver_options_prefix = 'pinit_' multilevelNonlinearSolver = NonlinearSol...
multilevelLinearSolver = KSP_petsc4py levelLinearSolver = KSP_petsc4py
random_line_split
pressureInitial_n.py
from proteus import * from proteus.default_n import * from pressureInitial_p import * triangleOptions = triangleOptions femSpaces = {0:pbasis} stepController=FixedStep #numericalFluxType = NumericalFlux.ConstantAdvection_Diffusion_SIPG_exterior #weak boundary conditions (upwind ?) matrix = LinearAlgebraTools.Spars...
else: multilevelLinearSolver = KSP_petsc4py levelLinearSolver = KSP_petsc4py parallelPartitioningType = parallelPartitioningType nLayersOfOverlapForParallel = nLayersOfOverlapForParallel nonlinearSmoother = None linearSmoother = None numericalFluxType = NumericalFlux.ConstantAdvection_...
multilevelLinearSolver = LinearSolvers.LU levelLinearSolver = LinearSolvers.LU
conditional_block
texture_draw.rs
#[macro_use] extern crate glium; use glium::Surface; mod support; macro_rules! texture_draw_test { ($test_name:ident, $tex_ty:ident, [$($dims:expr),+], $glsl_ty:expr, $glsl_value:expr, $rust_value:expr) => ( #[test]
let program = glium::Program::from_source(&display, " #version 110 attribute vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } ", &f...
fn $test_name() { let display = support::build_display(); let (vb, ib) = support::build_rectangle_vb_ib(&display);
random_line_split
v2wizardPage.component.ts
import { IController, module } from 'angular'; import { ModalWizard, IWizardPageState } from './ModalWizard'; /** * Wizard page directive * possible attributes: * - key (required): Any string value, unique within the wizard; it becomes the the hook to access the page state * through the wizard, e.g. wizard.g...
} const wizardPageComponent: ng.IComponentOptions = { bindings: { mandatory: '<', done: '<', markCleanOnView: '<', markCompleteOnView: '<', key: '@', label: '@', render: '<', }, transclude: true, templateUrl: require('./v2wizardPage.component.html'), controller: WizardPageControl...
{ this.render = this.render !== false; this.markCleanOnView = this.markCleanOnView !== false; this.markCompleteOnView = this.markCompleteOnView !== false; this.state = { blocked: false, current: false, rendered: this.render, done: this.done || !this.mandatory, dirty: false...
identifier_body
v2wizardPage.component.ts
import { IController, module } from 'angular'; import { ModalWizard, IWizardPageState } from './ModalWizard'; /** * Wizard page directive * possible attributes: * - key (required): Any string value, unique within the wizard; it becomes the the hook to access the page state * through the wizard, e.g. wizard.g...
* when set to false, registers the page with the wizard, but does not participate in the wizard flow. * To add the page to the flow, call wizard.includePage(key) * default: true * @type {boolean} */ public render: boolean; /** * Internal state of the page, initialized based on other public fields...
/**
random_line_split
v2wizardPage.component.ts
import { IController, module } from 'angular'; import { ModalWizard, IWizardPageState } from './ModalWizard'; /** * Wizard page directive * possible attributes: * - key (required): Any string value, unique within the wizard; it becomes the the hook to access the page state * through the wizard, e.g. wizard.g...
() { this.render = this.render !== false; this.markCleanOnView = this.markCleanOnView !== false; this.markCompleteOnView = this.markCompleteOnView !== false; this.state = { blocked: false, current: false, rendered: this.render, done: this.done || !this.mandatory, dirty: fa...
$onInit
identifier_name
Dialog.js
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditio...
/** @type {?WebInspector.View} */ WebInspector.Dialog._modalHostView = null; /** * @param {!WebInspector.View} view */ WebInspector.Dialog.setModalHostView = function(view) { WebInspector.Dialog._modalHostView = view; }; /** * FIXME: make utility method in Dialog, so clients use it instead of this getter. * M...
__proto__: WebInspector.Object.prototype }
random_line_split
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): m...
(rig, text): return rig.select(text) def seq(rig, num): return query(rig, '$sequence=%d' % num) def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
query
identifier_name
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): m...
def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
return query(rig, '$sequence=%d' % num)
identifier_body
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): m...
return rig @memoize(ignore = set([0])) def query(rig, text): return rig.select(text) def seq(rig, num): return query(rig, '$sequence=%d' % num) def rand_color(): func = lambda: random.randint(0, 255) / 255.0 return (func(), func(), func())
fireplace(rig)
conditional_block
core.py
#!/usr/bin/python2 # core.py # aoneill - 04/10/17 import sys import random import time import pauschpharos as PF import lumiversepython as L SEQ_LIM = 200 def memoize(ignore = None): if(ignore is None): ignore = set() def inner(func): cache = dict() def wrapper(*args): m...
query(rig, '$sequence=%d' % seq) def init(upload = True, run = True, wipe = True, fire = True): rig = L.Rig("/home/teacher/Lumiverse/PBridge.rig.json") rig.init() # Upload the blank template if(upload): blank() # Run if requested if(run): rig.run() # Wipe if requested if(w...
def fireplace(rig): # Warm up cache for seq in xrange(SEQ_LIM):
random_line_split
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
def get_build_packages(self) -> Set[str]: if not self.__build_packages: processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ...
if not self.__build_snaps: processor = grammar.GrammarProcessor( self._build_snap_grammar, self._project, repo.snaps.SnapPackage.is_valid_snap, ) self.__build_snaps = processor.process() return self.__build_snaps
identifier_body
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
(self) -> str: if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.proce...
get_source
identifier_name
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
return self.__build_packages def get_stage_packages(self) -> Set[str]: if not self.__stage_packages: processor = grammar.GrammarProcessor( self._stage_package_grammar, self._project, self._repo.is_valid, transformer=packa...
processor = grammar.GrammarProcessor( self._build_package_grammar, self._project, self._repo.build_package_is_valid, transformer=package_transformer, ) self.__build_packages = processor.process()
conditional_block
_part_grammar_processor.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
if not self.__source: # The grammar is array-based, even though we only support a single # source. processor = grammar.GrammarProcessor( self._source_grammar, self._project, lambda s: True ) source_array = processor.process() ...
def get_source(self) -> str:
random_line_split
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) gen...
lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): pixel_sum += (image[y][x]/255.0) #i...
identifier_body
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) gen...
#center the points (avoid leaving image bounds) mid_x_points = (min(all_positions[:,0]) + max(all_positions[:,0]))/2.0 mid_y_points = (min(all_positions[:,1]) + max(all_positions[:,1]))/2.0 for pos in all_positions: pos[0] -= (mid_x_points - w/2.0) pos[1] -= (m...
turn_delta = rand_sign() * randint(lo_turn_delta, hi_turn_delta) for s in range(steps_per_curve): curr_pos = all_positions[-1] delta_pos = np.array([pix_per_step * cos(curr_pos[2]), pix_per_step * sin(curr_pos[2]), turn_delta]) all_positions = np.append(all_...
conditional_block
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) gen...
#randomize start init_pos = np.array([randint(0, w - 1), randint(0, h - 1), randint(0, 360)]) all_positions = np.array([init_pos]) #dependent parameter (use float division) num_curves = int(rope_l_pixels/(steps_per_curve * pix_per_step * 1.0)) #point generation ...
image matrix with rope drawn [left label, right label] """ def get_rope_car(h = 420, w = 420, rope_l_pixels = 800 , rope_w_pixels = 8, pix_per_step = 10, steps_per_curve = 10, lo_turn_delta = 5, hi_turn_delta = 10):
random_line_split
synthetic_rope.py
import numpy as np import cv2 from scipy import interpolate from random import randint import IPython from alan.rgbd.basic_imaging import cos,sin from alan.synthetic.synthetic_util import rand_sign from alan.core.points import Point """ generates rope using non-holonomic car model dynamics (moves with turn radius) gen...
(label, bounds, image, rope_w_pixels): lb = [] ub = [] for dim in range(2): lb.append(int(max(0, label[dim] - rope_w_pixels))) ub.append(int(min(bounds[dim] - 1, label[dim] + rope_w_pixels))) pixel_sum = 0 for x in range(lb[0], ub[0]): for y in range(lb[1], ub[1]): ...
check_overlap
identifier_name
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramf...
(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: raise ValueError("you must p...
get_pft_verbose_name
identifier_name
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramf...
def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError("you must provide only one of you cmtkey or cmtnumber") if pftkey and pftnum: ra...
'''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[...
identifier_body
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramf...
else: # normal data line dline = line.strip().split("//") values = dline[0].split() comment = dline[1].strip().strip("//").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(val...
continue # Nothing to do...commented line
conditional_block
param_util.py
#!/usr/bin/env python # T. Carman # January 2017 import os import json def get_CMTs_in_file(aFile): ''' Gets a list of the CMTs found in a file. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramf...
# Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip("//").strip().split("//") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment d...
'''
random_line_split
customize_juropa_icc_libxc.py
compiler = './icc.py' mpicompiler = './icc.py' mpilinker = 'MPICH_CC=gcc mpicc' scalapack = True library_dirs += ['/opt/intel/Compiler/11.0/074/mkl/lib/em64t'] libraries = ['mkl_intel_lp64' ,'mkl_sequential' ,'mkl_core', 'mkl_lapack', 'mkl_scalapack_lp64', 'mkl_blacs_intelmpi_lp64', ...
define_macros += [('GPAW_NO_UNDERSCORE_CSCALAPACK', '1')] define_macros += [("GPAW_ASYNC",1)] define_macros += [("GPAW_MPI2",1)]
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
let square = rectangle::square(0.0, 0.0, 50.0); let rotation = self.rotation; let (x, y) = ((args.width / 2) as f64, (args.height / 2) as f64); self.gl.draw(args.viewport(), |c, gl| { // Clear the screen. clear(GREEN, gl); let t...
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct
{ gl: GlGraphics, // OpenGL drawing backend. rotation: f64 // Rotation for the square. } impl App { fn render(&mut self, args: &RenderArgs) { use graphics::*; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectan...
App
identifier_name
main.rs
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; pub struct App { gl: GlGraphics, // Ope...
if let Some(u) = e.update_args() { app.update(&u); } } }
{ app.render(&r); }
conditional_block
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number)....
def _bottles(self, number): if number == 0: return 'no more bottles' if number == 1: return '1 bottle' else: return '%d bottles' % number def _next_verse(self, current_verse): return current_verse - 1 if current_verse > 0 else 99
return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse))
identifier_body
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number)....
(self, current_verse): if current_verse == 0: return "Go to the store and buy some more, " else: return "Take %s down and pass it around, " % ( "one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse): return "%s of bee...
_action
identifier_name
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number)....
"one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse): return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse)) def _bottles(self, number): if number == 0: return 'no more bottles' if number == 1:...
return "Go to the store and buy some more, " else: return "Take %s down and pass it around, " % (
random_line_split
example.py
class Beer(object): def sing(self, first, last=0): verses = '' for number in reversed(range(last, first + 1)): verses += self.verse(number) + '\n' return verses def verse(self, number): return ''.join([ "%s of beer on the wall, " % self._bottles(number)....
else: return "Take %s down and pass it around, " % ( "one" if current_verse > 1 else "it" ) def _next_bottle(self, current_verse): return "%s of beer on the wall.\n" % self._bottles(self._next_verse(current_verse)) def _bottles(self, number): if...
return "Go to the store and buy some more, "
conditional_block
ngb-calendar-hebrew.ts
import {NgbDate} from '../ngb-date'; import {fromJSDate, NgbCalendar, NgbPeriod, toJSDate} from '../ngb-calendar'; import {Injectable} from '@angular/core'; import {isNumber} from '../../util/util'; import { fromGregorian, getDayNumberInHebrewYear, getDaysInHebrewMonth, isHebrewLeapYear, toGregorian, setHeb...
() { return 7; } getMonths(year?: number) { if (year && isHebrewLeapYear(year)) { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; } else { return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; } } getWeeksPerMonth() { return 6; } isValid(date?: NgbDate | null): boolean { if (date !=...
getDaysPerWeek
identifier_name
ngb-calendar-hebrew.ts
import {NgbDate} from '../ngb-date'; import {fromJSDate, NgbCalendar, NgbPeriod, toJSDate} from '../ngb-calendar'; import {Injectable} from '@angular/core'; import {isNumber} from '../../util/util'; import { fromGregorian, getDayNumberInHebrewYear, getDaysInHebrewMonth, isHebrewLeapYear, toGregorian, setHeb...
date = setHebrewMonth(date, number); date.day = 1; return date; case 'd': return setHebrewDay(date, number); default: return date; } } getPrev(date: NgbDate, period: NgbPeriod = 'd', number = 1) { return this.getNext(date, period, -number); } getWeekday(da...
case 'm':
random_line_split
ngb-calendar-hebrew.ts
import {NgbDate} from '../ngb-date'; import {fromJSDate, NgbCalendar, NgbPeriod, toJSDate} from '../ngb-calendar'; import {Injectable} from '@angular/core'; import {isNumber} from '../../util/util'; import { fromGregorian, getDayNumberInHebrewYear, getDaysInHebrewMonth, isHebrewLeapYear, toGregorian, setHeb...
getToday(): NgbDate { return fromGregorian(new Date()); } /** * @since 3.4.0 */ toGregorian(date: NgbDate): NgbDate { return fromJSDate(toGregorian(date)); } /** * @since 3.4.0 */ fromGregorian(date: NgbDate): NgbDate { return fromGregorian(toJSDate(date)); } }
{ const date = week[week.length - 1]; return Math.ceil(getDayNumberInHebrewYear(date) / 7); }
identifier_body
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def
(payload, **kwargs): """ Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL Tested against: * MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function...
tamper
identifier_name
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs):
""" Replaces instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' Requirement: * MySQL Tested against: * MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(...
identifier_body
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs): """ Replaces instances like 'CONCAT(...
return payload
payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),")
conditional_block
concat2concatws.py
#!/usr/bin/env python """ Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs): """ Replaces instances like 'CONCAT(...
* MySQL 5.0 Notes: * Useful to bypass very weak and bespoke web application firewalls that filter the CONCAT() function >>> tamper('CONCAT(1,2)') 'CONCAT_WS(MID(CHAR(0),0,0),1,2)' """ if payload: payload = payload.replace("CONCAT(", "CONCAT_WS(MID(CHAR(0),0,0),")...
Tested against:
random_line_split
import-crate-with-invalid-spans.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
identifier_body
import-crate-with-invalid-spans.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't crash when encountering this. let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32); }
main
identifier_name
import-crate-with-invalid-spans.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// aux-build:crate_with_invalid_spans.rs // pretty-expanded FIXME #23616 extern crate crate_with_invalid_spans; fn main() { // The AST of `exported_generic` stored in crate_with_invalid_spans's // metadata should contain an invalid span where span.lo > span.hi. // Let's make sure the compiler doesn't cra...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
spinner.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Component} from '@angular/core'; import {createGenericTestComponent} from '../../test/util/helpers'; import {NglSpinnersModule} from './module'; const createTestComponent = (html?: string) => createGenericTestComponent(TestComponent, html) as ...
function getSpinnerContainer(element: Element): HTMLDivElement { return <HTMLDivElement>element.firstElementChild; } describe('Spinner Component', () => { beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglSpinnersModule]})); it('should render a medium spinner', () =...
{ return <HTMLDivElement>element.querySelector('.slds-spinner'); }
identifier_body
spinner.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Component} from '@angular/core'; import {createGenericTestComponent} from '../../test/util/helpers'; import {NglSpinnersModule} from './module'; const createTestComponent = (html?: string) => createGenericTestComponent(TestComponent, html) as ...
{ container = true; }
TestComponent
identifier_name
spinner.spec.ts
import {TestBed, ComponentFixture} from '@angular/core/testing'; import {Component} from '@angular/core'; import {createGenericTestComponent} from '../../test/util/helpers'; import {NglSpinnersModule} from './module'; const createTestComponent = (html?: string) => createGenericTestComponent(TestComponent, html) as ...
function getSpinnerElement(element: Element): HTMLDivElement { return <HTMLDivElement>element.querySelector('.slds-spinner'); } function getSpinnerContainer(element: Element): HTMLDivElement { return <HTMLDivElement>element.firstElementChild; } describe('Spinner Component', () => { beforeEach(() => TestBed.con...
random_line_split
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_r...
"""Return the name of the device.""" return self._name @property def device_state_attributes(self): """Return the device specific state attributes.""" attrs = { ATTR_NODE_ID: self.node_id, ATTR_NODE_NAME: self._name, ATTR_MANUFACTURER_NAME: se...
@property def name(self):
random_line_split
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_r...
(self, value): """Handle a node activated event for this node.""" if self.hass is None: return self.hass.bus.fire( EVENT_NODE_EVENT, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_BASIC_...
node_event
identifier_name
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_r...
def get_node_statistics(self): """Retrieve statistics from the node.""" return self._network.manager.getNodeStatistics( self._network.home_id, self.node_id ) def node_changed(self): """Update node properties.""" attributes = {} stats = self.get_node...
"""Handle a changed node on the network.""" if node and node.node_id != self.node_id: return if args is not None and "nodeId" in args and args["nodeId"] != self.node_id: return # Process central scene activation if value is not None and value.command_class == COM...
identifier_body
node_entity.py
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_r...
self.hass.bus.fire( EVENT_SCENE_ACTIVATED, { ATTR_ENTITY_ID: self.entity_id, ATTR_NODE_ID: self.node.node_id, ATTR_SCENE_ID: scene_id, }, ) def central_scene_activated(self, scene_id, scene_data): """Handl...
return
conditional_block
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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 a...
return data.tostring() if data.buffer_info()[1] > 0 else None def deleteFile(self, usrFacingUrlPrefix): self._ensureTableExists() writer = self.__connection.create_batch_writer(self.__table) chunks = self._getNofChunks(usrFacingUrlPrefix) m = Mutation(usrFacingUrlPrefix) ...
if chunks_read != chunks: self.__log.error("did not read all the chunks from StaticFile Store")
random_line_split
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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 a...
(self): self._connect(self.__host, self.__port, self.__user, self.__password) def putFile(self, usrFacingUrlPrefix, hash_str, data): self._ensureTableExists() self._ensureNoDuplicates(usrFacingUrlPrefix) self._putHash(usrFacingUrlPrefix, hash_str) data_length = len(data) ...
reConnection
identifier_name
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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 a...
def _connect(self, host, port, user, password): try: self.__connection = Accumulo(host, port, user, password) self.__log.debug('Connected to StaticFile Store') except Exception as e: self.__log.exception('Error while connecting to StaticFile Store: %s' % str(e))...
self.__host = host self.__port = port self.__user = user self.__password = password self.__table = 'ezfrontend' self.__cf = 'static' self.__connection = None if logger is not None: self.__log = logger else: self.__log = logging.get...
identifier_body
ezRPStaticFileStore.py
# Copyright (C) 2013-2015 Computer Sciences Corporation # # 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 a...
def _ensureNoDuplicates(self, usrFacingUrlPrefix): ''' Ensure a single copy of file for a given usrFacingUrlPrefix ''' if self._getHash(usrFacingUrlPrefix) is not None: self.deleteFile(usrFacingUrlPrefix) def _putNofChunks(self, usrFacingUrlPrefix, length): ...
self.__log.info('table "{table}" does not exist in StaticFile Store. Creating the table'.format(table=self.__table)) self.__connection.create_table(self.__table) if not self.__connection.table_exists(self.__table): self.__log.error('Unable to ensure StaticFile Store table "{table...
conditional_block
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def kmeans_betacv(...
dist = dist_all_centers[doc_id, cluster] intra_dists.append(dist) intra_array[i] = np.mean(intra_dists) betacv = intra_array / inter_array cinterval = half_confidence_interval_size(betacv, confidence) return np.mean(betacv), cinterval
#Intra distance dist_all_centers = algorithm.transform(data) intra_dists = [] for doc_id, cluster in enumerate(labels):
random_line_split
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def kmeans_betacv(...
''' Computes the BetaCV for running Kmeans on the dataset. This method returns the BetaCV value and half of the size of the confidence interval for the same value (BetaCV is an average or the number of runs given). Arguments --------- data: matrix A matrix of observations. If this i...
identifier_body
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def
(data, num_cluster, batch_kmeans=False, n_runs = 10, confidence = 0.90): ''' Computes the BetaCV for running Kmeans on the dataset. This method returns the BetaCV value and half of the size of the confidence interval for the same value (BetaCV is an average or the number of runs given)...
kmeans_betacv
identifier_name
cluster.py
# -*- coding: utf8 ''' Common code for clustering tasks ''' from __future__ import division, print_function from sklearn.cluster import KMeans from sklearn.cluster import MiniBatchKMeans from sklearn.metrics import pairwise from vod.stats.ci import half_confidence_interval_size import numpy as np def kmeans_betacv(...
intra_array[i] = np.mean(intra_dists) betacv = intra_array / inter_array cinterval = half_confidence_interval_size(betacv, confidence) return np.mean(betacv), cinterval
dist = dist_all_centers[doc_id, cluster] intra_dists.append(dist)
conditional_block
locustfile.py
from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self): self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/") @task def pa...
class WebsiteUser(HttpLocust): task_set = WebsiteTasks min_wait = 5000 max_wait = 15000
def musica4(self): self.client.get("/musica/o-senhor-ressuscitou-aleluia/")
random_line_split
locustfile.py
from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self):
@task def page3(self): self.client.get("/sugestoes-para/4a-feira-da-quarta-semana-da-pascoa/") @task def page4(self): self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/") @task def musica1(self): self.client.get("/musica/ressuscitou/") @task ...
self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/")
identifier_body
locustfile.py
from locust import HttpLocust, TaskSet, task class WebsiteTasks(TaskSet): @task def page1(self): self.client.get("/sugestoes-para/6a-feira-da-quarta-semana-da-pascoa/") @task def page2(self): self.client.get("/sugestoes-para/5a-feira-da-quarta-semana-da-pascoa/") @task def pa...
(self): self.client.get("/sugestoes-para/3a-feira-da-quarta-semana-da-pascoa/") @task def musica1(self): self.client.get("/musica/ressuscitou/") @task def musica2(self): self.client.get("/musica/prova-de-amor-maior-nao-ha/") @task def musica3(self): self.client...
page4
identifier_name
apatite-postgres-connection.js
'use strict'; var ApatiteConnection = require('../apatite-connection.js'); var ApatiteError = require('../../error/apatite-error'); var ApatiteUtil = require('../../util.js'); var pgModuleName = 'pg'; var pg; if (ApatiteUtil.existsModule(pgModuleName)) // must be checked otherwise would get test discovery error for...
ialect) { super(dialect); this.poolEndConnCallback = null; } static getModuleName() { return pgModuleName; } static createNewPool(configOpts) { return new pg.Pool(configOpts) } basicConnect(onConnected) { var connectionOptions = this.dialect.connectionOp...
nstructor(d
identifier_name
apatite-postgres-connection.js
'use strict'; var ApatiteConnection = require('../apatite-connection.js'); var ApatiteError = require('../../error/apatite-error'); var ApatiteUtil = require('../../util.js'); var pgModuleName = 'pg'; var pg; if (ApatiteUtil.existsModule(pgModuleName)) // must be checked otherwise would get test discovery error for...
static getModuleName() { return pgModuleName; } static createNewPool(configOpts) { return new pg.Pool(configOpts) } basicConnect(onConnected) { var connectionOptions = this.dialect.connectionOptions; var connStr = `postgres://${connectionOptions.userName}:${connecti...
class ApatitePostgresConnection extends ApatiteConnection { constructor(dialect) { super(dialect); this.poolEndConnCallback = null; }
random_line_split
apatite-postgres-connection.js
'use strict'; var ApatiteConnection = require('../apatite-connection.js'); var ApatiteError = require('../../error/apatite-error'); var ApatiteUtil = require('../../util.js'); var pgModuleName = 'pg'; var pg; if (ApatiteUtil.existsModule(pgModuleName)) // must be checked otherwise would get test discovery error for...
else if (this.databaseConnection) { this.databaseConnection.end(); } onDisconnected(null); } basicExecuteSQLString(sqlStr, bindVariables, onExecuted, options) { var self = this; this.setDBConnection(function(connErr) { if (connErr) { ...
if (this.poolEndConnCallback) { this.poolEndConnCallback(); this.poolEndConnCallback = null; } }
conditional_block
widget.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
chart.service.function .apply(chart.service.caller, args) .then(response => { this.fetchData = false; this.results = response.data; }); }; } }; export default WidgetComponent;
{ args.splice(0,1); }
conditional_block
widget.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
}; export default WidgetComponent;
random_line_split
url_extractor.py
""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') ...
(html: str, base_url: str) -> List[str]: """Gets all valid links from a site and returns them as URIs (some links may be relative. If the URIs scraped here would go back into the system to have more URIs scraped from their HTML, we would need to filter out all those who are not HTTP or HTTPS. Also, ass...
_scrape_urls
identifier_name
url_extractor.py
""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') ...
async def _scrape_urls_from_queued_html(redis_pool: aioredis.RedisPool): _log.info('Processing HTML from queue...') while True: try: html_payload = await redis_queue.pop(redis_pool) _log.info('Processing HTML from URL %s', html_payload.url) scraped_urls = _scrape_...
"""Gets all valid links from a site and returns them as URIs (some links may be relative. If the URIs scraped here would go back into the system to have more URIs scraped from their HTML, we would need to filter out all those who are not HTTP or HTTPS. Also, assuming that many consumers and many producers ...
identifier_body