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 |
|---|---|---|---|---|
authconn.py | _fields = len (auth_info_required)
table = gtk.Table (num_fields, 2)
table.set_row_spacings (6)
table.set_col_spacings (6)
self.field_entry = []
for i in range (num_fields):
field = auth_info_required[i]
label = gtk.Label (_(self.AUTH_FIELD.get (field, fi... |
def _get_prompt_allowed (self, ):
return self._prompt_allowed
def _set_prompt_allowed (self, allowed):
self._prompt_allowed = allowed
def _set_lock (self, whether):
self._lock = whether
def _connect (self, allow_pk=True):
cups.setUser (self._use_user)
self._... | debugprint ("%s: Operation ended" % self)
self._operation_stack.pop () | identifier_body |
authconn.py | _entry)):
self.field_entry[i].set_text (auth_info[i])
def get_auth_info (self):
return map (lambda x: x.get_text (), self.field_entry)
def get_remember_password (self):
try:
return self.remember_checkbox.get_active ()
except AttributeError:
return Fa... | # prompt, we need to try as root but with no password
# first.
debugprint ("Authentication: Try as root")
self._use_user = 'root'
self._auth_called = False | random_line_split | |
authconn.py | self.creds[(host,port)]
except KeyError:
return None
global_authinfocache = _AuthInfoCache ()
class Connection:
def __init__ (self, parent=None, try_as_root=True, lock=False,
host=None, port=None, encryption=None):
if host != None:
cups.setServer (host)
... | self._gui_event.clear ()
gobject.timeout_add (1, self._show_not_authorized_dialog)
self._gui_event.wait () | conditional_block | |
authconn.py | num_fields = len (auth_info_required)
table = gtk.Table (num_fields, 2)
table.set_row_spacings (6)
table.set_col_spacings (6)
self.field_entry = []
for i in range (num_fields):
field = auth_info_required[i]
label = gtk.Label (_(self.AUTH_FIELD.get (field... | (self, forbidden=False):
self._has_failed = True
self._forbidden = forbidden
def _password_callback (self, prompt):
debugprint ("Got password callback")
if self._cancel or self._auth_called:
return ''
self._auth_called = True
self._prompt = prompt
... | _failed | identifier_name |
libvecpf.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... |
build.make(self.sourcedir, make='./configure')
build.make(self.sourcedir)
def test(self):
"""
Execute self test of libvecpf library
"""
results = build.run_make(self.sourcedir, extra_args='check',
process_kwargs={'ignore_status': Tru... | """
Libvecpf is a "Vector Printf Library"
"""
def setUp(self):
"""
Build libvecpf
Source:
http://github.com/Libvecpf/libvecpf.git
"""
smm = SoftwareManager()
for package in ['gcc', 'make']:
if not smm.check_installed(package) and not smm.... | identifier_body |
libvecpf.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | (self):
"""
Build libvecpf
Source:
http://github.com/Libvecpf/libvecpf.git
"""
smm = SoftwareManager()
for package in ['gcc', 'make']:
if not smm.check_installed(package) and not smm.install(package):
self.cancel('%s is needed for the ... | setUp | identifier_name |
libvecpf.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | 'https://github.com/Libvecpf/libvecpf'
'/archive/master.zip'], expire='7d')
archive.extract(tarball, self.workdir)
self.sourcedir = os.path.join(self.workdir, 'libvecpf-master')
build.make(self.sourcedir, make='./configure')
... | if not smm.check_installed(package) and not smm.install(package):
self.cancel('%s is needed for the test to be run' % package)
tarball = self.fetch_asset('libvecpf.zip', locations=[ | random_line_split |
libvecpf.py | #!/usr/bin/env python
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... | self.fail('Test failed with following:%s' % failures) | conditional_block | |
lattice.rs | // Copyright 2012 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 ... | try!(sub.tys(a, v));
try!(sub.tys(b, v));
Ok(())
}
}
impl<'a, 'tcx> LatticeDir<'tcx> for Glb<'a, 'tcx> {
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> cres<'tcx, ()> {
let sub = self.sub();
try!(sub.tys(v, a));
try!(sub.tys(v, b));
Ok((... | let sub = self.sub(); | random_line_split |
lattice.rs | // Copyright 2012 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 ... |
}
pub fn super_lattice_tys<'tcx, L:LatticeDir<'tcx>+Combine<'tcx>>(this: &L,
a: Ty<'tcx>,
b: Ty<'tcx>)
-> cres<'tcx, Ty<'tc... | {
let sub = self.sub();
try!(sub.tys(v, a));
try!(sub.tys(v, b));
Ok(())
} | identifier_body |
lattice.rs | // Copyright 2012 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 ... | <'tcx, L:LatticeDir<'tcx>+Combine<'tcx>>(this: &L,
a: Ty<'tcx>,
b: Ty<'tcx>)
-> cres<'tcx, Ty<'tcx>>
{
debug!("{}.lattice... | super_lattice_tys | identifier_name |
DateTimeText.debug.js | //# © 2004-2006 Nick Campbell, All Rights Reserved. This code is hereby licensed under the terms of the LGPL (http://www.gnu.org/copyleft/lesser.html).
//# <DebugCode>
//#### If all of the required Cn objects do not exist, popup the related error message
if (typeof(Cn) == 'undefined' || ! Cn.Renderer || ! Cn.Rend... | Now:'Now',
AM:'am',
PM:'pm',
Delimiter:':',
DaySuffixes:['st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st'],
aDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
cDays:['Su','Mo','Tu','We','Th','... | NextYear:'Next Year',
Close:'Close',
Clear:'Clear',
| random_line_split |
DateTimeText.debug.js | //# © 2004-2006 Nick Campbell, All Rights Reserved. This code is hereby licensed under the terms of the LGPL (http://www.gnu.org/copyleft/lesser.html).
//# <DebugCode>
//#### If all of the required Cn objects do not exist, popup the related error message
if (typeof(Cn) == 'undefined' || ! Cn.Renderer || ! Cn.Rend... |
//# </DebugCode>
//########################################################################################################################
//# Supplemental Errors class - Errors.Messages
//#
//# NOTE: The "WeekOfYearCalculation", "SystemName" and "LanguageCode" are included on the querystring to this scr... |
//alert("Cn.Renderer.Form.DateTime.Text: [DEVELOPER] 'Cn/Renderer/Form/DateTime.js' must be included before referencing this code.");
}
| conditional_block |
kmerge_impl.rs | use crate::size_hint;
use crate::Itertools;
use alloc::vec::Vec;
use std::iter::FusedIterator;
use std::mem::replace;
use std::fmt;
/// Head element and Tail iterator pair
///
/// `PartialEq`, `Eq`, `PartialOrd` and `Ord` are implemented by comparing sequences based on
/// first items (which are guaranteed to exist).... |
impl<I, F> Clone for KMergeBy<I, F>
where I: Iterator + Clone,
I::Item: Clone,
F: Clone,
{
clone_fields!(heap, less_than);
}
impl<I, F> Iterator for KMergeBy<I, F>
where I: Iterator,
F: KMergePredicate<I::Item>
{
type Item = I::Item;
fn next(&mut self) -> Option<Sel... | {
let iter = iterable.into_iter();
let (lower, _) = iter.size_hint();
let mut heap: Vec<_> = Vec::with_capacity(lower);
heap.extend(iter.filter_map(|it| HeadTail::new(it.into_iter())));
heapify(&mut heap, |a, b| less_than.kmerge_pred(&a.head, &b.head));
KMergeBy { heap, less_than }
} | identifier_body |
kmerge_impl.rs | use crate::size_hint;
use crate::Itertools;
use alloc::vec::Vec;
use std::iter::FusedIterator;
use std::mem::replace;
use std::fmt;
/// Head element and Tail iterator pair
///
/// `PartialEq`, `Eq`, `PartialOrd` and `Ord` are implemented by comparing sequences based on
/// first items (which are guaranteed to exist).... | #[derive(Clone, Debug)]
pub struct KMergeByLt;
impl<T: PartialOrd> KMergePredicate<T> for KMergeByLt {
fn kmerge_pred(&mut self, a: &T, b: &T) -> bool {
a < b
}
}
impl<T, F: FnMut(&T, &T)->bool> KMergePredicate<T> for F {
fn kmerge_pred(&mut self, a: &T, b: &T) -> bool {
self(a, b)
}
}... | fn kmerge_pred(&mut self, a: &T, b: &T) -> bool;
}
| random_line_split |
kmerge_impl.rs | use crate::size_hint;
use crate::Itertools;
use alloc::vec::Vec;
use std::iter::FusedIterator;
use std::mem::replace;
use std::fmt;
/// Head element and Tail iterator pair
///
/// `PartialEq`, `Eq`, `PartialOrd` and `Ord` are implemented by comparing sequences based on
/// first items (which are guaranteed to exist).... |
}
/// Hints at the size of the sequence, same as the `Iterator` method.
fn size_hint(&self) -> (usize, Option<usize>) {
size_hint::add_scalar(self.tail.size_hint(), 1)
}
}
impl<I> Clone for HeadTail<I>
where I: Iterator + Clone,
I::Item: Clone
{
clone_fields!(head, tail);
}
... | {
None
} | conditional_block |
kmerge_impl.rs | use crate::size_hint;
use crate::Itertools;
use alloc::vec::Vec;
use std::iter::FusedIterator;
use std::mem::replace;
use std::fmt;
/// Head element and Tail iterator pair
///
/// `PartialEq`, `Eq`, `PartialOrd` and `Ord` are implemented by comparing sequences based on
/// first items (which are guaranteed to exist).... | <I, F>
where I: Iterator,
{
heap: Vec<HeadTail<I>>,
less_than: F,
}
impl<I, F> fmt::Debug for KMergeBy<I, F>
where I: Iterator + fmt::Debug,
I::Item: fmt::Debug,
{
debug_fmt_fields!(KMergeBy, heap);
}
/// Create an iterator that merges elements of the contained iterators.
///
/// Equival... | KMergeBy | identifier_name |
index.d.ts | // Type definitions for @storybook/addon-info 5.2
// Project: https://github.com/storybookjs/storybook, https://github.com/storybookjs/storybook/tree/master/addons/info
// Definitions by: Mark Kornblum <https://github.com/mkornblum>
// Mattias Wikstrom <https://github.com/fyrkant>
// Kev... | /**
* @deprecated "marksyConf" option has been renamed to "components"
*/
marksyConf?: object;
maxPropsIntoLine?: number;
maxPropObjectKeys?: number;
maxPropArrayLength?: number;
maxPropStringLength?: number;
TableComponent?: ComponentType<TableComponentOptionProps>;
excludedPr... | propTablesExclude?: Array<ComponentType<any>>;
styles?: object;
components?: {
[key: string]: ComponentType<any>
}; | random_line_split |
addAudios.component.ts | import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { environment } from '../../../../../../environments/environment';
import { AudioDataService } from '../..... |
}, 600);
});
}
// Load more
loadMore() {
this.loadingMoreData = true;
this.data.rowsDefault++;
let data = {
user: this.sessionData.current.id,
type: 'default',
rows: this.data.rowsDefault,
cuantity: environment.cuantity
}
this.audioDataService.default(data)
.subscribe(res => {
... | {
this.loadMoreData = (res.length < environment.cuantity) ? false : true;
this.noData = false;
this.data.list = res;
} | conditional_block |
addAudios.component.ts | import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { environment } from '../../../../../../environments/environment';
import { AudioDataService } from '../..... | if (res.length == 0) {
this.noData = true;
} else {
this.loadMoreData = (res.length < environment.cuantity) ? false : true;
this.noData = false;
this.data.list = res;
}
}, 600);
});
}
// Load more
loadMore() {
this.loadingMoreData = true;
this.data.rowsDefault++;
... | {
this.data.rowsDefault = 0;
this.loadingData = true;
this.data.list = [];
this.noData = false;
this.loadMoreData = false;
this.loadingMoreData = false;
let data = {
user: user,
type: 'default',
rows: this.data.rowsDefault,
cuantity: environment.cuantity
}
this.audioDataService.default(d... | identifier_body |
addAudios.component.ts | import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { environment } from '../../../../../../environments/environment';
import { AudioDataService } from '../..... | this.data.list = res;
}
}, 600);
});
}
// Load more
loadMore() {
this.loadingMoreData = true;
this.data.rowsDefault++;
let data = {
user: this.sessionData.current.id,
type: 'default',
rows: this.data.rowsDefault,
cuantity: environment.cuantity
}
this.audioDataService.defaul... | random_line_split | |
addAudios.component.ts | import { Component, OnInit, ViewChild, Inject } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { environment } from '../../../../../../environments/environment';
import { AudioDataService } from '../..... | implements OnInit {
public sessionData: any;
public translations: any;
public environment: any = environment;
public noData: boolean;
public loadingData: boolean;
public loadMoreData: boolean;
public loadingMoreData: boolean;
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
public dialogRef: MatDi... | MainNewPublicationAddAudiosComponent | identifier_name |
by-value-self-argument-in-trait-impl.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (self) -> int {
zzz();
self
}
}
struct Struct {
x: uint,
y: uint,
}
impl Trait for Struct {
fn method(self) -> Struct {
zzz();
self
}
}
impl Trait for (f64, int, int, f64) {
fn method(self) -> (f64, int, int, f64) {
zzz();
self
}
}
impl Tra... | method | identifier_name |
by-value-self-argument-in-trait-impl.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn zzz() {()}
| {
let _ = (1111 as int).method();
let _ = Struct { x: 2222, y: 3333 }.method();
let _ = (4444.5, 5555, 6666, 7777.5).method();
let _ = (@8888).method();
} | identifier_body |
by-value-self-argument-in-trait-impl.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
// debugger:finish
// debugger:print self->val
// check:$4 = 8888
// debugger:continue
trait Trait {
fn method(self) -> Self;
}
impl Trait for int {
fn method(self) -> int {
zzz();
self
}
}
struct Struct {
x: uint,
y: uint,
}
impl Trait for Struct {
fn method(self) -> Struct... | random_line_split | |
app.js | /**
* Module dependencies.
*/
var express = require('express'),
http = require('http'),
path = require('path'),
mongoose = require('mongoose'),
config = require('./config'),
routes = require('./routes/routes');
// connect to local mongodb database
mongoose.connect('mongodb://' + config.MONGODB_IP + '... | //console.log('【日志】连接到数据库:' + config.MONGODB_DATABASE_NAME);
} else {
throw err;
}
});
//attach lister to connected event
mongoose.connection.once('connected', function() {
console.log('【日志】连接到数据库:' + config.MONGODB_DATABASE_NAME);
});
var app = express();
// 修改文件后缀
app.engine('.html', require('ej... | if (!err) {
| random_line_split |
app.js | /**
* Module dependencies.
*/
var express = require('express'),
http = require('http'),
path = require('path'),
mongoose = require('mongoose'),
config = require('./config'),
routes = require('./routes/routes');
// connect to local mongodb database
mongoose.connect('mongodb://' + config.MONGODB_IP + '... | er to connected event
mongoose.connection.once('connected', function() {
console.log('【日志】连接到数据库:' + config.MONGODB_DATABASE_NAME);
});
var app = express();
// 修改文件后缀
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
// 所有环境
app.set('port', process.env.PORT || config.WEB_SERVER_... | );
//attach list | conditional_block |
ng-minmax.js | function | (value) {
return angular.isUndefined(value) || value === '' || value === null || value !== value;
}
angular.module('Aggie')
.directive('ngMin', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
scope.$watch(attr.ngMin, function () {
ct... | isEmpty | identifier_name |
ng-minmax.js | function isEmpty(value) |
angular.module('Aggie')
.directive('ngMin', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
scope.$watch(attr.ngMin, function () {
ctrl.$setViewValue(ctrl.$viewValue);
});
var minValidator = function (value) {
var mi... | {
return angular.isUndefined(value) || value === '' || value === null || value !== value;
} | identifier_body |
ng-minmax.js | function isEmpty(value) {
return angular.isUndefined(value) || value === '' || value === null || value !== value;
}
angular.module('Aggie')
.directive('ngMin', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
scope.$watch(attr.ngMin, function... |
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
};
})
.directive('ngMax', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
scope.$watch(attr.ngMax, function () {
ctrl.$setViewValue(ctrl.... | {
ctrl.$setValidity('ngMin', true);
return value;
} | conditional_block |
ng-minmax.js | function isEmpty(value) {
return angular.isUndefined(value) || value === '' || value === null || value !== value;
}
angular.module('Aggie')
.directive('ngMin', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
scope.$watch(attr.ngMin, function... | restrict: 'A',
require: 'ngModel',
link: function (scope, elem, attr, ctrl) {
scope.$watch(attr.ngMax, function () {
ctrl.$setViewValue(ctrl.$viewValue);
});
var maxValidator = function (value) {
var max = scope.$eval(attr.ngMax) || Infinity;
if (!isEmpty(value) && ... | };
})
.directive('ngMax', function () {
return { | random_line_split |
net.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 ... |
/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
io::Error::from_os_error(unsafe { c::WSAGetLastError() })
}
/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
/// and if so, returns the last error from the Windows socket interface. . This
///... | {
static START: Once = ONCE_INIT;
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(0x202, // version 2.2
&mut data);
assert_eq!(ret, 0);
rt::at_exit(|| { c::WSACleanup(); })
});
} | identifier_body |
net.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 ... | pub type wrlen_t = i32;
pub struct Socket(libc::SOCKET);
/// Checks whether the Windows socket interface has been started already, and
/// if not, starts it.
pub fn init() {
static START: Once = ONCE_INIT;
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAS... | use sys_common::AsInner;
| random_line_split |
net.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 ... | () {
static START: Once = ONCE_INIT;
START.call_once(|| unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(0x202, // version 2.2
&mut data);
assert_eq!(ret, 0);
rt::at_exit(|| { c::WSACleanup(); })
});
}
/// Returns t... | init | identifier_name |
importer_test.py | from StringIO import StringIO
import textwrap
import importer
def test_import_csv():
current = StringIO(textwrap.dedent('''\
status,qty,type,transaction_date,posting_date,description,amount
A,,,2016/11/02,,This is a test,$4.53
'''))
new = StringIO(textwrap.dedent('''\
... | 'Summary': 'description',
'Amount': 'amount'
}
importer.save_csv(current, new, mapping, '%m/%d/%Y')
lines = current.getvalue().splitlines()
assert lines[0].rstrip() == 'status,qty,type,transaction_date,posting_date,description,amount'
assert lines[1].rstrip() == 'N,2,,2007/05/02,,R... | '''))
mapping = {
'Trans Date': 'transaction_date', | random_line_split |
importer_test.py | from StringIO import StringIO
import textwrap
import importer
def | ():
current = StringIO(textwrap.dedent('''\
status,qty,type,transaction_date,posting_date,description,amount
A,,,2016/11/02,,This is a test,$4.53
'''))
new = StringIO(textwrap.dedent('''\
"Trans Date", "Summary", "Amount"
5/2/2007, Regal Theaters, $15... | test_import_csv | identifier_name |
importer_test.py | from StringIO import StringIO
import textwrap
import importer
def test_import_csv():
|
assert lines[0].rstrip() == 'status,qty,type,transaction_date,posting_date,description,amount'
assert lines[1].rstrip() == 'N,2,,2007/05/02,,Regal Theaters,$15.99'
assert lines[2].rstrip() == 'A,,,2016/11/02,,This is a test,$4.53'
assert len(lines) == 3
| current = StringIO(textwrap.dedent('''\
status,qty,type,transaction_date,posting_date,description,amount
A,,,2016/11/02,,This is a test,$4.53
'''))
new = StringIO(textwrap.dedent('''\
"Trans Date", "Summary", "Amount"
5/2/2007, Regal Theaters, $15.99
... | identifier_body |
SpringTransition.js | /* 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/.
*
* Owner: david@famo.us
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
var PE = require('../p... | * @constructor
*
* @param {Number|Array} [state=0] Initial state
*/
function SpringTransition(state) {
state = state || 0;
this.endState = new Vector(state);
this.initState = new Vector();
this._dimensions = undefined;
this._restTolerance = 1e-10;
this._absRestTolerance = this._re... | * SpringTransition is a method of transitioning between two values (numbers,
* or arrays of numbers) with a bounce. The transition will overshoot the target
* state depending on the parameters of the transition.
*
* @class SpringTransition | random_line_split |
SpringTransition.js | /* 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/.
*
* Owner: david@famo.us
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
var PE = require('../p... | (v) {
this.particle.setVelocity(v);
}
function _getParticlePosition() {
return (this._dimensions === 0)
? this.particle.getPosition1D()
: this.particle.getPosition();
}
function _getParticleVelocity() {
return (this._dimensions === 0)
? this.particle.getVelocity1D()
: this.... | _setParticleVelocity | identifier_name |
SpringTransition.js | /* 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/.
*
* Owner: david@famo.us
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
var PE = require('../p... |
function _getParticlePosition() {
return (this._dimensions === 0)
? this.particle.getPosition1D()
: this.particle.getPosition();
}
function _getParticleVelocity() {
return (this._dimensions === 0)
? this.particle.getVelocity1D()
: this.particle.getVelocity();
}
function _setC... | {
this.particle.setVelocity(v);
} | identifier_body |
SpringTransition.js | /* 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/.
*
* Owner: david@famo.us
* @license MPL 2.0
* @copyright Famous Industries, Inc. 2014
*/
var PE = require('../p... |
}
function _setupDefinition(definition) {
var defaults = SpringTransition.DEFAULT_OPTIONS;
if (definition.period === undefined) definition.period = defaults.period;
if (definition.dampingRatio === undefined) definition.dampingRatio = defaults.dampingRatio;
if (definition.velocity === undef... | {
_setParticlePosition.call(this, this.endState);
_setParticleVelocity.call(this, [0,0,0]);
_sleep.call(this);
} | conditional_block |
TransferProfile.js | /**
* Open Payments Cloud Application API
* Open Payments Cloud API
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (ty... |
if (data.hasOwnProperty('type')) {
obj['type'] = ApiClient.convertToType(data['type'], 'String');
}
if (data.hasOwnProperty('active')) {
obj['active'] = ApiClient.convertToType(data['active'], 'Boolean');
}
if (data.hasOwnProperty('tags')) {
obj['tags'] = ApiClient... | {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
} | conditional_block |
TransferProfile.js | /**
* Open Payments Cloud Application API
* Open Payments Cloud API
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
*/
(function(root, factory) {
if (ty... | * @const
*/
"DEACTIVATE": "DEACTIVATE" };
return exports;
})); | "ACTIVATE": "ACTIVATE",
/**
* value: "DEACTIVATE" | random_line_split |
fat.rs | //! A Mach-o fat binary is a multi-architecture binary container
use core::fmt;
if_std! {
use std::fs::File;
use std::io::{self, Read};
}
use crate::error;
use crate::mach::constants::cputype::{CpuSubType, CpuType, CPU_ARCH_ABI64, CPU_SUBTYPE_MASK};
use scroll::{Pread, Pwrite, SizeWith};
pub const FAT_MAGIC... | (&self) -> CpuSubType {
self.cpusubtype & !CPU_SUBTYPE_MASK
}
/// Returns the capabilities of the CPU
pub fn cpu_caps(&self) -> u32 {
(self.cpusubtype & CPU_SUBTYPE_MASK) >> 24
}
/// Whether this fat architecture header describes a 64-bit binary
pub fn is_64(&self) -> bool {
... | cpusubtype | identifier_name |
fat.rs | //! A Mach-o fat binary is a multi-architecture binary container
use core::fmt;
if_std! {
use std::fs::File;
use std::io::{self, Read};
}
use crate::error;
use crate::mach::constants::cputype::{CpuSubType, CpuType, CPU_ARCH_ABI64, CPU_SUBTYPE_MASK};
use scroll::{Pread, Pwrite, SizeWith};
pub const FAT_MAGIC... |
}
}
/// Returns the cpu type
pub fn cputype(&self) -> CpuType {
self.cputype
}
/// Returns the cpu subtype with the capabilities removed
pub fn cpusubtype(&self) -> CpuSubType {
self.cpusubtype & !CPU_SUBTYPE_MASK
}
/// Returns the capabilities of the CPU
... | {
log::warn!("invalid `FatArch` offset");
&[]
} | conditional_block |
fat.rs | //! A Mach-o fat binary is a multi-architecture binary container
use core::fmt;
if_std! {
use std::fs::File;
use std::io::{self, Read};
}
use crate::error;
use crate::mach::constants::cputype::{CpuSubType, CpuType, CPU_ARCH_ABI64, CPU_SUBTYPE_MASK};
use scroll::{Pread, Pwrite, SizeWith};
pub const FAT_MAGIC... |
}
| {
let arch = bytes.pread_with::<FatArch>(offset, scroll::BE)?;
Ok(arch)
} | identifier_body |
fat.rs | //! A Mach-o fat binary is a multi-architecture binary container
use core::fmt;
if_std! {
use std::fs::File;
use std::io::{self, Read};
}
use crate::error;
use crate::mach::constants::cputype::{CpuSubType, CpuType, CPU_ARCH_ABI64, CPU_SUBTYPE_MASK};
use scroll::{Pread, Pwrite, SizeWith};
pub const FAT_MAGIC... | /// Parse a mach-o fat header from the `bytes`
pub fn parse(bytes: &[u8]) -> error::Result<FatHeader> {
Ok(bytes.pread_with::<FatHeader>(0, scroll::BE)?)
}
}
#[repr(C)]
#[derive(Clone, Copy, Default, Pread, Pwrite, SizeWith)]
/// The Mach-o `FatArch` always has its data bigendian
pub struct FatArch... | random_line_split | |
utils.py | <will@thames.id.au>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublice... | (filepath):
idx = filepath.find('roles/')
if idx < 0:
return ''
role = filepath[idx+6:]
role = role[:role.find('/')]
return role
def _kv_to_dict(v):
(command, args, kwargs) = tokenize(v)
return (dict(module=command, module_arguments=args, **kwargs))
def normalize_task(task):
... | rolename | identifier_name |
utils.py | Thames <will@thames.id.au>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... | return role_path
def _look_for_role_files(basedir, role):
role_path = _rolepath(basedir, role)
if not role_path:
return []
results = []
for th in ['tasks', 'handlers', 'meta']:
for ext in ('.yml', '.yaml'):
thpath = os.path.join(role_path, th, 'main' + ext)
... | random_line_split | |
utils.py | <will@thames.id.au>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublice... |
for path_option in possible_paths:
if os.path.isdir(path_option):
role_path = path_option
break
return role_path
def _look_for_role_files(basedir, role):
role_path = _rolepath(basedir, role)
if not role_path:
return []
results = []
for th in ['tasks... | loc = os.path.expanduser(loc)
possible_paths.append(ansible.utils.path_dwim(loc, role)) | conditional_block |
utils.py | <will@thames.id.au>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublice... |
def tokenize(line):
result = list()
tokens = line.lstrip().split(" ")
if tokens[0] == '-':
tokens = tokens[1:]
if tokens[0] == 'action:' or tokens[0] == 'local_action:':
tokens = tokens[1:]
command = tokens[0].replace(":", "")
args = list()
kwargs = dict()
for arg in ... | result = []
fh = None
for pluginfile in glob.glob(os.path.join(directory, '[A-Za-z]*.py')):
pluginname = os.path.basename(pluginfile.replace('.py', ''))
try:
fh, filename, desc = imp.find_module(pluginname, [directory])
mod = imp.load_module(pluginname, fh, filename, de... | identifier_body |
kindck-inherited-copy-bound.rs | // Test that Copy bounds inherited by trait are checked.
//
// revisions: curr object_safe_for_dispatch
#![cfg_attr(object_safe_for_dispatch, feature(object_safe_for_dispatch))]
#![feature(box_syntax)]
use std::any::Any;
trait Foo : Copy {
fn foo(&self) |
}
impl<T:Copy> Foo for T {
}
fn take_param<T:Foo>(foo: &T) { }
fn a() {
let x: Box<_> = box 3;
take_param(&x); //[curr]~ ERROR E0277
//[object_safe_for_dispatch]~^ ERROR E0277
}
fn b() {
let x: Box<_> = box 3;
let y = &x;
let z = &x as &dyn Foo;
//[curr]~^ ERROR E0038
//[curr]~| ERR... | {} | identifier_body |
kindck-inherited-copy-bound.rs | // Test that Copy bounds inherited by trait are checked.
//
// revisions: curr object_safe_for_dispatch
#![cfg_attr(object_safe_for_dispatch, feature(object_safe_for_dispatch))]
#![feature(box_syntax)]
use std::any::Any;
trait Foo : Copy {
fn foo(&self) {}
}
impl<T:Copy> Foo for T {
}
fn take_param<T:Foo>(foo:... | () {
let x: Box<_> = box 3;
let y = &x;
let z = &x as &dyn Foo;
//[curr]~^ ERROR E0038
//[curr]~| ERROR E0038
//[object_safe_for_dispatch]~^^^ ERROR E0038
}
fn main() { }
| b | identifier_name |
kindck-inherited-copy-bound.rs | // Test that Copy bounds inherited by trait are checked.
//
// revisions: curr object_safe_for_dispatch
#![cfg_attr(object_safe_for_dispatch, feature(object_safe_for_dispatch))]
#![feature(box_syntax)]
use std::any::Any;
trait Foo : Copy {
fn foo(&self) {}
}
impl<T:Copy> Foo for T {
}
fn take_param<T:Foo>(foo:... | //[object_safe_for_dispatch]~^^^ ERROR E0038
}
fn main() { } | let z = &x as &dyn Foo;
//[curr]~^ ERROR E0038
//[curr]~| ERROR E0038 | random_line_split |
webpack.config.development.ts | /// <reference path='webpack.fix.d.ts' />
import * as HtmlWebpackPlugin from 'html-webpack-plugin'
import * as path from 'path'
import * as webpack from 'webpack'
import { CheckerPlugin } from 'awesome-typescript-loader'
import baseConfig from './webpack.config.base'
const merge = require('webpack-merge') // tslint:... | filename: 'index.html',
inject: 'body',
template: path.resolve(__dirname, '../index.html')
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('development')
}
})
]
}
export default merge(baseConfig, config) | random_line_split | |
ask.js | //you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate inp... | }
else {
context.done(null, { "error": "vname doesn't match current versions" });
return null;
}
/* SAMPLE DATA, uncomment if you want to use it
vname_version = 'v1';
vname_components = ['brown','bear','Chicago'];
... | {
var nameRequest = event["body-json"];
hash.update(event["context"]["source-ip"]);
var hashedIpAddress = hash.digest('hex');
var blocking_string = hashedIpAddress;
var session_expiry = 3600;
if (nameRequest.vname) {
var v1ValidationFilter = /^The ([a-z]|[A-Z... | identifier_body |
ask.js | //you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate inp... | function sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry) {
var payload = { "vname_version": vname_version, "vname_components": vname_components, "blocking_string": blocking_string, "session_expiry_sec": session_expiry };
payload = JSON.stringify(payload);
... | return null;
}
| random_line_split |
ask.js | //you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate inp... | () {
var nameRequest = event["body-json"];
hash.update(event["context"]["source-ip"]);
var hashedIpAddress = hash.digest('hex');
var blocking_string = hashedIpAddress;
var session_expiry = 3600;
if (nameRequest.vname) {
var v1ValidationFilter = /^The ([a-z]|[... | configureParams | identifier_name |
ask.js | //you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate inp... | vname_components = ['brown','bear','Chicago'];
blocking_string = 0383176601762cf74cb95607034b9c7712a431325074396e073d7eb4e5206edc; //just a hash of the user's IP address, you could use a cookie or deviceId as well
session_expiry = 600; // 10 minute connection
*/
... | {
var v1ValidationFilter = /^The ([a-z]|[A-Z])+ ([a-z]|[A-Z])+ of ([a-z]|[A-Z]|[0-9]|-| )+([a-z]|[A-Z]|[0-9])$/i;
if (v1ValidationFilter.test(nameRequest.vname)) {
var vname_components = [];
var vname_version = 'v1';
var vnameMacroParts = nameReque... | conditional_block |
sidepanel_folder.js | 'use strict';
angular.module('arethusa.core').directive('sidepanelFolder', [
'sidepanel',
'$window',
'translator',
function(sidepanel, $window, translator) {
return {
scope: {},
link: function (scope, element, attrs) {
var win = angular.element($window);
scope.translations = tr... | () {
var icon = sidepanel.folded ? 'expand' : 'compress';
var text = sidepanel.folded ? 'show' : 'fold';
var key = arethusaUtil.formatKeyHint(sidepanel.activeKeys.toggle);
scope.iconClass = 'fi-arrows-' + icon;
element.attr('title', scope.translations[text]() + " " + k... | setIconClassAndTitle | identifier_name |
sidepanel_folder.js | 'use strict';
angular.module('arethusa.core').directive('sidepanelFolder', [
'sidepanel',
'$window',
'translator',
function(sidepanel, $window, translator) {
return {
scope: {},
link: function (scope, element, attrs) {
var win = angular.element($window);
scope.translations = tr... | }
});
},
template: '<i ng-class="iconClass"/>'
};
}
]); | element.hide();
foldWatch(); | random_line_split |
sidepanel_folder.js | 'use strict';
angular.module('arethusa.core').directive('sidepanelFolder', [
'sidepanel',
'$window',
'translator',
function(sidepanel, $window, translator) {
return {
scope: {},
link: function (scope, element, attrs) {
var win = angular.element($window);
scope.translations = tr... |
}, true);
function setIconClassAndTitle() {
var icon = sidepanel.folded ? 'expand' : 'compress';
var text = sidepanel.folded ? 'show' : 'fold';
var key = arethusaUtil.formatKeyHint(sidepanel.activeKeys.toggle);
scope.iconClass = 'fi-arrows-' + icon;
e... | {
setIconClassAndTitle();
} | conditional_block |
sidepanel_folder.js | 'use strict';
angular.module('arethusa.core').directive('sidepanelFolder', [
'sidepanel',
'$window',
'translator',
function(sidepanel, $window, translator) {
return {
scope: {},
link: function (scope, element, attrs) {
var win = angular.element($window);
scope.translations = tr... |
element.on('click', function () {
sidepanel.toggle();
scope.$apply(setIconClassAndTitle());
});
scope.sp = sidepanel;
var foldWatch = function() {};
scope.$watch('sp.active', function(newVal) {
if (newVal) {
element.show();
... | {
var icon = sidepanel.folded ? 'expand' : 'compress';
var text = sidepanel.folded ? 'show' : 'fold';
var key = arethusaUtil.formatKeyHint(sidepanel.activeKeys.toggle);
scope.iconClass = 'fi-arrows-' + icon;
element.attr('title', scope.translations[text]() + " " + key)... | identifier_body |
custom-type.js | var inspector = require('../');
// Custom type schema
var personValidation = {
type: 'object',
properties: {
firstname: { type: 'string', minLength: 1 },
lastname: { type: 'string', minLength: 1 },
age: { type: 'integer', gt: 0, lte: 120 }
}
};
// Custom Validation ($type)
var customValidation = {
// $type w... | }
};
// Extend SchemaInspector.Validator
inspector.Validation.extend(customValidation);
var data = {
firstname: ' sebastien ',
lastname: 'chopin ',
age: '21'
};
var schema = { $type: 'person' };
var result = inspector.validate(schema, data);
if (!result.valid)
console.log(result.format()); // Property @.age: mu... | return this.report(result.format()); | random_line_split |
from_string.rs | use malachite_base::num::conversion::string::from_string::digit_from_display_byte;
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::{unsigned_gen, unsigned_gen_var_10};
use malachite_base_test_util::runner::Runner;
pub(crate) fn register(runner: &mut Run... |
fn demo_digit_from_display_byte(gm: GenMode, config: GenConfig, limit: usize) {
for b in unsigned_gen().get(gm, &config).take(limit) {
println!(
"digit_from_display_byte({}) = {:?}",
b,
digit_from_display_byte(b)
);
}
}
fn demo_digit_from_display_byte_targe... | {
register_demo!(runner, demo_digit_from_display_byte);
register_demo!(runner, demo_digit_from_display_byte_targeted);
} | identifier_body |
from_string.rs | use malachite_base::num::conversion::string::from_string::digit_from_display_byte; | use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::{unsigned_gen, unsigned_gen_var_10};
use malachite_base_test_util::runner::Runner;
pub(crate) fn register(runner: &mut Runner) {
register_demo!(runner, demo_digit_from_display_byte);
register_demo!... | random_line_split | |
from_string.rs | use malachite_base::num::conversion::string::from_string::digit_from_display_byte;
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::{unsigned_gen, unsigned_gen_var_10};
use malachite_base_test_util::runner::Runner;
pub(crate) fn | (runner: &mut Runner) {
register_demo!(runner, demo_digit_from_display_byte);
register_demo!(runner, demo_digit_from_display_byte_targeted);
}
fn demo_digit_from_display_byte(gm: GenMode, config: GenConfig, limit: usize) {
for b in unsigned_gen().get(gm, &config).take(limit) {
println!(
... | register | identifier_name |
cache.py | # coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2021 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
return None
def update(self, job):
"""Update last_run, next_run, and last_run_result for an existing job.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute('''UPDATE jobs
SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''',... | return dict(zip(
("id", "description", "last-run", "next-run", "last-run-result"),
item)) | conditional_block |
cache.py | # coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2021 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | :param dict job: The job dictionary
:returns: True
"""
self.cur.execute('''UPDATE jobs
SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''', (
job["last-run"], job["next-run"], job["last-run-result"], job["id"]))
def add_job(self, job):
"""Adds... |
return None
def update(self, job):
"""Update last_run, next_run, and last_run_result for an existing job. | random_line_split |
cache.py | # coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2021 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... |
def add_result(self, job):
"""Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute(
"INSERT INTO history VALUES(?,?,?,?)",
(job["id"], job["description"], job["last-run"], job["last-run-r... | """Adds a new job into the cache.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute("INSERT INTO jobs VALUES(?,?,?,?,?)", (
job["id"], job["description"], job["last-run"], job["next-run"], job["last-run-result"]))
return True | identifier_body |
cache.py | # coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2021 yutiansut/QUANTAXIS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation th... | (self, job):
"""Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute(
"INSERT INTO history VALUES(?,?,?,?)",
(job["id"], job["description"], job["last-run"], job["last-run-result"]))
r... | add_result | identifier_name |
ini.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | (v):
if "#" not in v:
try:
return ast.literal_eval(v)
# Using explicit exceptions.
# Likely a string that literal_eval does not like. We wil then just set it.
except ValueError:
# For some reason this was thought to be malformed.
... | _parse_value | identifier_name |
ini.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... |
# [webservers]
# alpha
# beta:2345
# gamma sudo=True user=root
# delta asdf=jkl favcolor=red
def _add_allgroup_children(self):
for group in self.groups.values():
if group.depth == 0 and group.name != 'all':
self.groups['all'].add_child_group(group)
d... | if "#" not in v:
try:
return ast.literal_eval(v)
# Using explicit exceptions.
# Likely a string that literal_eval does not like. We wil then just set it.
except ValueError:
# For some reason this was thought to be malformed.
... | identifier_body |
ini.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... |
hostname = tokens[0]
port = C.DEFAULT_REMOTE_PORT
# Three cases to check:
# 0. A hostname that contains a range pesudo-code and a port
# 1. A hostname that contains just a port
if hostname.count(":") > 1:
... | continue | conditional_block |
ini.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | self.hosts[hn] = host
if len(tokens) > 1:
for t in tokens[1:]:
if t.startswith('#'):
break
try:
(k,v) = t.split("=", 1)
... | host = self.hosts[hn]
else:
host = Host(name=hn, port=port) | random_line_split |
clv_insured_seq.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | (self, default=None):
default = dict(default or {})
default.update({'code': '/',})
return super(clv_insured, self).copy(default)
| copy | identifier_name |
clv_insured_seq.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... |
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str = "%s.%s.%s.%s.%s-%s" % (str(code[0]) + str(code[1]),
str(code[2]) + s... | code.insert(0, 0) | conditional_block |
clv_insured_seq.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | code_form = code_str[17 - code_len:21]
elif code_len > 6 and code_len <= 9:
code_form = code_str[16 - code_len:21]
elif code_len > 9 and code_len <= 12:
code_form = code_str[15 - code_len:21]
elif code_len > 12 and code_len <= 14:
code_form = code_str[14 - code_len:21]
re... | code = map(int, str(code_seq))
code_len = len(code)
while len(code) < 14:
code.insert(0, 0)
while len(code) < 16:
n = sum([(len(code) + 1 - i) * v for i, v in enumerate(code)]) % 11
if n > 1:
f = 11 - n
else:
f = 0
code.append(f)
code_str =... | identifier_body |
clv_insured_seq.py | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | # #
# 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 ... | # the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. # | random_line_split |
CmfRegisteredSaga.component.js | import { useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import { start, stop } from '../../actions/saga';
export function CmfRegisteredSagaComponent({
sagaId,
startSaga,
stopSaga,
sagaAttributes,
componentId = 'default',
ch... | startSaga: (event, properties) => dispatch(start(event, properties)),
stopSaga: (event, properties) => dispatch(stop(event, properties)),
});
export const CmfRegisteredSaga = connect(null, mapDispatchToProps)(CmfRegisteredSagaComponent); |
const mapDispatchToProps = dispatch => ({ | random_line_split |
CmfRegisteredSaga.component.js | import { useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import { start, stop } from '../../actions/saga';
export function CmfRegisteredSagaComponent({
sagaId,
startSaga,
stopSaga,
sagaAttributes,
componentId = 'default',
ch... |
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return children;
}
CmfRegisteredSagaComponent.propTypes = {
sagaId: PropTypes.string.isRequired,
startSaga: PropTypes.func.isRequired,
stopSaga: PropTypes.func.isRequired,
sagaAttributes: PropTypes.any,
componentId: PropTypes.string,
chil... | {
stopSaga({ type: 'WILL_UNMOUNT', componentId: id }, { saga: sagaId, componentId });
} | conditional_block |
CmfRegisteredSaga.component.js | import { useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import { start, stop } from '../../actions/saga';
export function CmfRegisteredSagaComponent({
sagaId,
startSaga,
stopSaga,
sagaAttributes,
componentId = 'default',
ch... |
CmfRegisteredSagaComponent.propTypes = {
sagaId: PropTypes.string.isRequired,
startSaga: PropTypes.func.isRequired,
stopSaga: PropTypes.func.isRequired,
sagaAttributes: PropTypes.any,
componentId: PropTypes.string,
children: PropTypes.node,
};
CmfRegisteredSagaComponent.displayName = 'CmfRegisteredSagaComponent... | {
const id = useMemo(v4, []);
// If we pass the sagaId, we use the cmf registry
useEffect(() => {
if (sagaId) {
startSaga(
{ type: 'DID_MOUNT', componentId: id },
{ saga: sagaId, componentId, ...sagaAttributes },
);
}
return () => {
if (sagaId) {
stopSaga({ type: 'WILL_UNMOUNT', componentI... | identifier_body |
CmfRegisteredSaga.component.js | import { useEffect, useMemo } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import { start, stop } from '../../actions/saga';
export function | ({
sagaId,
startSaga,
stopSaga,
sagaAttributes,
componentId = 'default',
children = null,
}) {
const id = useMemo(v4, []);
// If we pass the sagaId, we use the cmf registry
useEffect(() => {
if (sagaId) {
startSaga(
{ type: 'DID_MOUNT', componentId: id },
{ saga: sagaId, componentId, ...sagaAttrib... | CmfRegisteredSagaComponent | identifier_name |
webdriver.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
if permission not in permissions:
return None
value = permissions[permission]
if not isinstance(value, bool):
return None
return value
# First available in Safari 11.1 and Safari Technology Preview 42.
def debug(self):
self.execute("ATTACH_DEB... | return None | conditional_block |
webdriver.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# First available in Safari 11.1 and Safari Technology Preview 42.
def debug(self):
self.execute("ATTACH_DEBUGGER")
self.execute_script("debugger;")
| payload = self.execute("GET_PERMISSIONS")["value"]
permissions = payload["permissions"]
if not permissions:
return None
if permission not in permissions:
return None
value = permissions[permission]
if not isinstance(value, bool):
return None
... | identifier_body |
webdriver.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# First available in Safari 11.1 and Safari Technology Preview 41.
def set_permission(self, permission, value):
if not isinstance(value, bool):
raise WebDriverException("Value of a session permission must be set to True or False.")
payload = {}
payload[permission] = value
... | # https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/WebDriverEndpointDoc/Commands/Commands.html | random_line_split |
webdriver.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | (RemoteWebDriver):
"""
Controls the SafariDriver and allows you to drive the browser.
"""
def __init__(self, port=0, executable_path="/usr/bin/safaridriver", reuse_service=False,
desired_capabilities=DesiredCapabilities.SAFARI, quiet=False,
keep_alive=True):
"... | WebDriver | identifier_name |
imag_test.py | # -*- coding: utf-8 -*-
# python+selenium识别验证码
#
import re
import requests
import pytesseract
from selenium import webdriver
from PIL import Image,Image
import time
#
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://higo.flycua.com/hp/html/login.html")
driver.implicitly_wait(30)
# 下面用户名和密码涉及到我个... | conditional_block | ||
imag_test.py | # -*- coding: utf-8 -*-
# python+selenium识别验证码
#
import re
import requests
import pytesseract
from selenium import webdriver
from PIL import Image,Image
import time
#
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://higo.flycua.com/hp/html/login.html")
driver.implicitly_wait(30)
# 下面用户名和密码涉及到我个... | # 浏览器页面截屏
driver.get_screenshot_as_file(screenImg)
# 定位验证码位置及大小
location = driver.find_element_by_name('authImage').location
size = driver.find_element_by_name('authImage').size
# 下面四行我都在后面加了数字,理论上是不用加的,但是不加我这截的不是验证码那一块的图,可以看保存的截图,根据截图修改截图位置
left = location['x'] + 530
top = location['... | screenImg = "H:\screenImg.png" | random_line_split |
engine.py | /*Owner & Copyrights: Vance King Saxbe. A.*/""" Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxb... |
with open('conf/symbolname.conf') as fille:
synamelist = fille.read().splitlines()
fille.close()
timetorun = 1800
cycle = 1
while("TRUE"):
with open('conf/urls.conf') as openedfile:
fileaslist = openedfile.read().splitlines()
openedfile.close()
a_lock = _thread.allocate_lock()
... | random_line_split | |
engine.py | /*Owner & Copyrights: Vance King Saxbe. A.*/""" Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxb... | elif lisj[1] =='y':
thr.append(_thread.start_new_thread(yahooquotemachine.actionking, (a_lock,start1, lisj[0].replace('"',''),database+lisj[2].replace('"',''),0,synamelist,1,0,timetorun) ))
else:
... | lisj = lines.split('", "')
mtime = markettime[lisj[2].replace('"','')]
mktime = mtime.split("-")
if mktime[1] < mktime[0]:
righto = mktime[1].split(":")
close = str(str(int(righto[0])+... | conditional_block |
test_pvconstants.py | from pvmismatch import *
import os
import numpy as np
BASEDIR = os.path.dirname(__file__)
def test_pvconst_npts_setter():
|
def test_minimum_current_close_to_max_voc_gh110():
"""
Tests that minimum current in ``calcSeries`` is reasonably close to the
maximum open circuit current of all cells in module. This came up in GitHub
issue 110 that the resolution of the plots, and hence the underlying data,
at high cell temper... | """Test pvconst property and setter methods"""
pvconst = pvconstants.PVconstants()
assert pvconst.npts == pvconstants.NPTS
assert len(pvconst.pts) == pvconst.npts
assert pvconst.pts[0] == 0
assert pvconst.pts[-1] == 1
assert len(pvconst.negpts) == pvconst.npts
assert pvconst.negpts[0] == 1
... | identifier_body |
test_pvconstants.py | from pvmismatch import *
import os
import numpy as np
BASEDIR = os.path.dirname(__file__)
def test_pvconst_npts_setter():
"""Test pvconst property and setter methods"""
pvconst = pvconstants.PVconstants()
assert pvconst.npts == pvconstants.NPTS
assert len(pvconst.pts) == pvconst.npts
assert pvco... | pvsys = pvsystem.PVsystem()
pvsys.setTemps(388)
expected = np.loadtxt(os.path.join(BASEDIR, 'gh110.dat'))
calculated = np.concatenate(
[[pvsys.Isys], [pvsys.Vsys], [pvsys.Psys]], axis=0).T
assert np.allclose(expected, calculated)
return calculated
if __name__ == '__main__':
calcula... | """ | random_line_split |
test_pvconstants.py | from pvmismatch import *
import os
import numpy as np
BASEDIR = os.path.dirname(__file__)
def test_pvconst_npts_setter():
"""Test pvconst property and setter methods"""
pvconst = pvconstants.PVconstants()
assert pvconst.npts == pvconstants.NPTS
assert len(pvconst.pts) == pvconst.npts
assert pvco... | ():
"""
Tests that minimum current in ``calcSeries`` is reasonably close to the
maximum open circuit current of all cells in module. This came up in GitHub
issue 110 that the resolution of the plots, and hence the underlying data,
at high cell temperature was too coarse.
"""
pvsys = pvsystem... | test_minimum_current_close_to_max_voc_gh110 | identifier_name |
test_pvconstants.py | from pvmismatch import *
import os
import numpy as np
BASEDIR = os.path.dirname(__file__)
def test_pvconst_npts_setter():
"""Test pvconst property and setter methods"""
pvconst = pvconstants.PVconstants()
assert pvconst.npts == pvconstants.NPTS
assert len(pvconst.pts) == pvconst.npts
assert pvco... | calculated = test_minimum_current_close_to_max_voc_gh110()
np.savetxt(os.path.join(BASEDIR, 'gh110.dat'), calculated) | conditional_block | |
command_executor.py | import sublime
import os
import subprocess
import platform
from .bootstrapper import get_config
from .notifier import log_info, log_error, log_fail
from .thread_progress import run_progress_indicator
from .command_thread import CommandThread
_appbuilder_path = []
def | (command, on_data=None, on_done=None, show_progress=True,
in_progress_message="Loading", success_message="", failure_message = "",
show_status=True, filter_empty_args=True, no_save=False, **kwargs):
appbuilder_path = _get_appbuilder_path()
if appbuilder_path == None:
on_done(False)
retur... | run_command | identifier_name |
command_executor.py | import sublime
import os
import subprocess
import platform
from .bootstrapper import get_config
from .notifier import log_info, log_error, log_fail
from .thread_progress import run_progress_indicator
from .command_thread import CommandThread
_appbuilder_path = []
def run_command(command, on_data=None, on_done=None, ... | if not _appbuilder_path:
if platform.system() == "Windows":
_appbuilder_path.append(_find_win_node_path())
_appbuilder_path.append(_find_win_appbuilder_path())
elif platform.system() == "Darwin":
osx_node_path = get_config("osx_node_path")
osx_appbuild... | random_line_split | |
command_executor.py | import sublime
import os
import subprocess
import platform
from .bootstrapper import get_config
from .notifier import log_info, log_error, log_fail
from .thread_progress import run_progress_indicator
from .command_thread import CommandThread
_appbuilder_path = []
def run_command(command, on_data=None, on_done=None, ... |
return thread
def show_quick_panel(window, items, on_done):
window.show_quick_panel(items, on_done)
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
Backported from Python 2.7 as it's implemented as pure python on stdlib.
>>> chec... | message = kwargs.get("status_message", False) or " ".join(command)
sublime.status_message(message) | conditional_block |
command_executor.py | import sublime
import os
import subprocess
import platform
from .bootstrapper import get_config
from .notifier import log_info, log_error, log_fail
from .thread_progress import run_progress_indicator
from .command_thread import CommandThread
_appbuilder_path = []
def run_command(command, on_data=None, on_done=None, ... | return os.environ["PATH"].split(os.pathsep) | identifier_body | |
x86_64-linux-macos.rs | /* 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/. */
#[allow(unused_mut)]
#[inline(always)]
pub unsafe fn request(
default: usize,
request: usize,
... | arg4: usize,
arg5: usize) -> usize {
let args: [usize; 6] = [request, arg1, arg2, arg3, arg4, arg5];
let mut result: usize;
// Valgrind notices this magic instruction sequence and interprets
// it as a kind of hypercall. When not running under Valgrind,
// the instructions do noth... | arg2: usize,
arg3: usize, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.