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 |
|---|---|---|---|---|
errors.rs | // Copyright 2016 Jonas mg
// See the 'AUTHORS' file at the top-level directory for a full list of authors.
//
// 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/.
use s... | fn cause(&self) -> Option<&error::Error> {
None
}
fn description(&self) -> &str {
match *self {
AsciiError::ControlChar(_) => "contain ASCII control character",
AsciiError::NonAscii(_) => "contain non US-ASCII character",
}
}
}
impl fmt::Display for Ascii... |
impl error::Error for AsciiError { | random_line_split |
utils.py | results, url):
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_COPY_ERROR_DESK,
user=user,
src=src,
results=results,
url=url,
can_change_preferences=False,
)
mails.send_mail(
to_addr=user.username,
mail=mails.AR... | (func):
cache = {}
@functools.wraps(func)
def wrapper(node):
if node._id not in cache:
osf_storage = node.get_addon('osfstorage')
file_tree = osf_storage._get_file_tree(user=node.creator)
cache[node._id] = _do_get_file_map(file_tree)
return func(node, cac... | _memoize_get_file_map | identifier_name |
utils.py | , url):
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_COPY_ERROR_DESK,
user=user,
src=src,
results=results,
url=url,
can_change_preferences=False,
)
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_CO... |
def send_archiver_uncaught_error_mails(src, user, results, url):
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_UNCAUGHT_ERROR_DESK,
user=user,
src=src,
results=results,
can_change_preferences=False,
url=url,
)
mails.send_mai... | mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_FILE_NOT_FOUND_DESK,
can_change_preferences=False,
user=user,
src=src,
results=results,
url=url,
)
mails.send_mail(
to_addr=user.username,
mail=mails.ARCHIVE_FILE_NOT_F... | identifier_body |
utils.py | results, url):
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_COPY_ERROR_DESK,
user=user,
src=src,
results=results,
url=url,
can_change_preferences=False,
)
mails.send_mail(
to_addr=user.username,
mail=mails.AR... | )
orig_node = value['nodeId']
file_map = get_file_map(node)
for sha256, file_info, node_id in file_map:
registered_from_id = AbstractNode.load(node_id).registered_from._id
if sha256 == orig_sha256 and registered_from_id == orig_node and orig_name == file_info['name']:
return ... | } | random_line_split |
utils.py | can_change_preferences=False,
mimetype='html',
)
def send_archiver_file_not_found_mails(src, user, results, url):
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.ARCHIVE_FILE_NOT_FOUND_DESK,
can_change_preferences=False,
user=user,
src=src... | paths = paths + [('{}.{}.value'.format(prefix, qid), p) for p in path['properties']] | conditional_block | |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 la... | (io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config)... | sync_arguments | identifier_name |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 la... | if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
... | random_line_split | |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 la... | cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
_client: Arc<BlockChainClient>,
_snapshot_service: Arc<SnapshotService>,
_provide... | {
let service_config = ServiceConfiguration {
sync: sync_cfg,
net: net_cfg,
io_path: io_path.to_owned(),
};
// initialisation payload is passed via stdin
let service_payload = serialize(&service_config).expect("Any binary-derived struct is serializable by definition");
// client service url and logging set... | identifier_body |
modules.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 la... |
if let Some(ref file) = log_settings.file {
cli_args.push("--log-file".to_owned());
cli_args.push(file.to_owned());
}
BootArgs::new().stdin(service_payload).cli(cli_args)
}
#[cfg(feature="ipc")]
pub fn sync
(
hypervisor_ref: &mut Option<Hypervisor>,
sync_cfg: SyncConfig,
net_cfg: NetworkConfiguration,
... | {
cli_args.push("-l".to_owned());
cli_args.push(mode.to_owned());
} | conditional_block |
dispersion.py | # Natural Language Toolkit: Dispersion Plots
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A utility for displaying lexical dispersion.
"""
def dispersion_plot(text, words, ignore_case=False, title="Lexic... |
points = [(x,y) for x in range(len(text_to_comp))
for y in range(len(words_to_comp))
if text_to_comp[x] == words_to_comp[y]]
if points:
x, y = list(zip(*points))
else:
x = y = ()
pylab.plot(x, y, "b|", scalex=.1)
pylab.yticks(list(range(len(w... | words_to_comp = words
text_to_comp = text | conditional_block |
dispersion.py | # Natural Language Toolkit: Dispersion Plots
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A utility for displaying lexical dispersion.
"""
def dispersion_plot(text, words, ignore_case=False, title="Lexic... | from matplotlib import pylab
except ImportError:
raise ValueError('The plot function requires matplotlib to be installed.'
'See http://matplotlib.org/')
text = list(text)
words.reverse()
if ignore_case:
words_to_comp = list(map(str.lower, words))
te... |
try: | random_line_split |
dispersion.py | # Natural Language Toolkit: Dispersion Plots
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A utility for displaying lexical dispersion.
"""
def dispersion_plot(text, words, ignore_case=False, title="Lexic... | if ignore_case:
words_to_comp = list(map(str.lower, words))
text_to_comp = list(map(str.lower, text))
else:
words_to_comp = words
text_to_comp = text
points = [(x,y) for x in range(len(text_to_comp))
for y in range(len(words_to_comp))
... | """
Generate a lexical dispersion plot.
:param text: The source text
:type text: list(str) or enum(str)
:param words: The target words
:type words: list of str
:param ignore_case: flag to set if case should be ignored when searching text
:type ignore_case: bool
"""
try:
fro... | identifier_body |
dispersion.py | # Natural Language Toolkit: Dispersion Plots
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A utility for displaying lexical dispersion.
"""
def | (text, words, ignore_case=False, title="Lexical Dispersion Plot"):
"""
Generate a lexical dispersion plot.
:param text: The source text
:type text: list(str) or enum(str)
:param words: The target words
:type words: list of str
:param ignore_case: flag to set if case should be ignored when s... | dispersion_plot | identifier_name |
tools.js | i=0;i<sPW.length;i++){
//密码模式
Modes|=CharMode(sPW.charCodeAt(i));
}
return bitTotal(Modes);
}
function checkChinese(str){
var reg = /.*[\u4e00-\u9fa5]+.*$/;
return reg.test(str);
}
function checkPhone(str){
var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
return reg.test(str);
}
function GetRequest(){
var url =... | }
function base64decode(str) {
var c1, c2, c3, c4;
var i, len,
out;
len = str.length;
i = 0;
out = "";
while (i < len) {
do {
c1 = base64decodechars[str.charCodeAt(i++) & 0xff];
} while (i < len && c1 == -1);
... | dechars.charAt(c1 >> 2);
out += base64encodechars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64encodechars.charAt(c1 >> 2);
out += base64encodechar... | conditional_block |
tools.js | (i=0;i<sPW.length;i++){
//密码模式
Modes|=CharMode(sPW.charCodeAt(i));
}
return bitTotal(Modes);
}
function checkChinese(str){
var reg = /.*[\u4e00-\u9fa5]+.*$/;
return reg.test(str);
}
function checkPhone(str){
var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
return reg.test(str);
}
function GetRequest(){
var url... | out += base64encodechars.charAt(c1 >> 2);
out += base64encodechars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
out += base64encodechars.charAt((c2 & 0xf) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
... | c2 = str.charCodeAt(i++);
if (i == len) { | random_line_split |
tools.js | reg.test(str);
}
function checkPhone(str){
var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
return reg.test(str);
}
function GetRequest(){
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < s... | (i=0;i<sPW.length;i++){
//密码模式
Modes|=CharMode(sPW.charCodeAt(i));
}
return bitTotal(Modes);
}
function checkChinese(str){
var reg = /.*[\u4e00-\u9fa5]+.*$/;
return | identifier_body | |
tools.js | um & 1) modes++;
num>>>=1;
}
return modes;
}
//返回强度级别
function checkStrong(sPW){
if (sPW.length<=4)
return 0; //密码太短
Modes=0;
for (i=0;i<sPW.length;i++){
//密码模式
Modes|=CharMode(sPW.charCodeAt(i));
}
return bitTotal(Modes);
}
function checkChinese(str){
var reg = /.*[\u4e00-\u9fa5]+.*$/;
... |
if (n | identifier_name | |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... |
}
| {
trace!("Successfully called stat() for: {:?}", filename);
Ok(())
} | conditional_block |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | unsafe { libc::close(fd) };
let custom_error = Error::new(ErrorKind::Other, "Maximum allowed file size for prefetching exceeded!");
Err(custom_error)
} else {
// Manually fault in all pages
let result = unsafe { libc::readahead(fd, 0, stat.st_size as usize) };
if re... | {
trace!("Caching file: {:?}", filename);
let file = File::open(filename)?;
let fd = file.into_raw_fd();
// We are interested in file size
let mut stat: libc::stat = unsafe { std::mem::zeroed() };
unsafe {
libc::fstat(fd, &mut stat);
};
if stat.st_mode & libc::S_ISUID == libc:... | identifier_body |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | Err(std::io::Error::last_os_error())
} else {
trace!("Successfully called posix_fadvise() for: {:?}", filename);
let result = unsafe {
libc::madvise(
addr as *mut libc::c_void,
... | random_line_split | |
memory.rs | /*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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 Softwar... | {
pub filename: PathBuf,
pub addr: usize,
pub len: usize,
}
impl MemoryMapping {
pub fn new(filename: &Path, addr: usize, len: usize) -> MemoryMapping {
MemoryMapping {
filename: PathBuf::from(filename),
addr,
len,
}
}
}
#[cfg(target_pointer_wid... | MemoryMapping | identifier_name |
dropck_tarena_cycle_checked.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 ... | (&self) -> usize {
match self.get() {
None => 1,
Some(c) => c.id.count(),
}
}
}
impl<'a> C<'a> {
fn new() -> C<'a> {
C { id: Id::new(), v: Vec::new() }
}
}
fn f<'a>(arena: &'a TypedArena<C<'a>>) {
let c1 = arena.alloc(C::new());
let c2 = arena.alloc(... | count | identifier_name |
dropck_tarena_cycle_checked.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 ... | let c = s::next_count();
println!("building Id {}", c);
Id { orig_count: c, count: c }
}
pub fn count(&self) -> usize {
println!("Id::count on {} returns {}", self.orig_count, self.count);
self.count
}
}
impl Drop for Id {
... | impl Id {
pub fn new() -> Id { | random_line_split |
TSVtoVCF.py | #!/usr/bin/env python2.7
import argparse,sys
import time as t
parser = argparse.ArgumentParser()
parser.add_argument("--inTSV", help="")
parser.add_argument("--outVCF", help="")
args = parser.parse_args()
def toVCF(TSV, VCF):
|
toVCF(args.inTSV, args.outVCF) | '''
:param TSV:
:param VCF:
:return:
'''
out = open(VCF, 'w')
for line in open(TSV):
if line.startswith('##'):
out.writelines(line)
else:
if 'CHROM' in line:
head = line.strip().split(' ')
out.writelines("#CHROM\tPOS\tID\tRE... | identifier_body |
TSVtoVCF.py | #!/usr/bin/env python2.7
import argparse,sys
import time as t
parser = argparse.ArgumentParser()
parser.add_argument("--inTSV", help="")
parser.add_argument("--outVCF", help="")
args = parser.parse_args()
| :return:
'''
out = open(VCF, 'w')
for line in open(TSV):
if line.startswith('##'):
out.writelines(line)
else:
if 'CHROM' in line:
head = line.strip().split(' ')
out.writelines("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n")
... | def toVCF(TSV, VCF):
'''
:param TSV:
:param VCF: | random_line_split |
TSVtoVCF.py | #!/usr/bin/env python2.7
import argparse,sys
import time as t
parser = argparse.ArgumentParser()
parser.add_argument("--inTSV", help="")
parser.add_argument("--outVCF", help="")
args = parser.parse_args()
def | (TSV, VCF):
'''
:param TSV:
:param VCF:
:return:
'''
out = open(VCF, 'w')
for line in open(TSV):
if line.startswith('##'):
out.writelines(line)
else:
if 'CHROM' in line:
head = line.strip().split(' ')
out.writelines("#CH... | toVCF | identifier_name |
TSVtoVCF.py | #!/usr/bin/env python2.7
import argparse,sys
import time as t
parser = argparse.ArgumentParser()
parser.add_argument("--inTSV", help="")
parser.add_argument("--outVCF", help="")
args = parser.parse_args()
def toVCF(TSV, VCF):
'''
:param TSV:
:param VCF:
:return:
'''
out = open(VCF, 'w')
f... |
out.close()
toVCF(args.inTSV, args.outVCF) | for i in range(4,len(line)):
line[i] = head[i]+'='+line[i]
out.writelines('\t'.join([line[0],line[1],'.',line[2],line[3],'.','.',';'.join(line[4:])])+'\n') | conditional_block |
lorentzAttractor.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | (self,runInfoDict,inputFiles):
self.sigma = 10.0
self.rho = 28.0
self.beta = 8.0/3.0
return
def run(self, Input):
"""
Run
@ In, self, object, variable-storing object
@ In, Input, dict, additional variables
@ Out, None
"""
max_time = 0.03
t_step = 0.01
numberTimeSteps = int(max_tim... | initialize | identifier_name |
lorentzAttractor.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
firstVar = Input['awful.variable+name']
secondVar = Input['@another|awful name']
self.z0 = Input['z0']
self.firstOut[0] = firstVar
self.secondOut[0] = secondVar
self.z[0] = Input['z0']
self.time[0]= 0
for t in range (numberTimeSteps-1):
self.time[t+1] = self.time[t] + t_step
self.firstOut[t... | self.z = np.zeros(numberTimeSteps)
self.time = np.zeros(numberTimeSteps) | random_line_split |
lorentzAttractor.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
def run(self, Input):
"""
Run
@ In, self, object, variable-storing object
@ In, Input, dict, additional variables
@ Out, None
"""
max_time = 0.03
t_step = 0.01
numberTimeSteps = int(max_time/t_step)
self.firstOut = np.zeros(numberTimeSteps)
self.secondOut = np.zeros(numberTimeSteps)
... | self.sigma = 10.0
self.rho = 28.0
self.beta = 8.0/3.0
return | identifier_body |
lorentzAttractor.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
# aliased outputs
Input['x@'] = self.firstOut
Input['y[1]'] = self.secondOut
| self.time[t+1] = self.time[t] + t_step
self.firstOut[t+1] = self.firstOut[t] + self.sigma*(self.secondOut[t]-self.firstOut[t]) * t_step
self.secondOut[t+1] = self.secondOut[t] + (self.firstOut[t]*(self.rho-self.z[t])-self.secondOut[t]) * t_step
self.z[t+1] = self.z[t] + (self.firstOut[t]*self.secon... | conditional_block |
nulldummy.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
Genera... |
def run_test(self):
self.address = self.nodes[0].getnewaddress()
self.ms_address = self.nodes[0].addmultisigaddress(1,[self.address])
self.wit_address = self.nodes[0].addwitnessaddress(self.address)
self.wit_ms_address = self.nodes[0].addwitnessaddress(self.ms_address)
Net... | self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
extra_args=[['-whitelist=127.0.0.1', '-walletprematurewitness']]) | identifier_body |
nulldummy.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
Genera... |
tx.vin[0].scriptSig = CScript(newscript)
tx.rehash()
class NULLDUMMYTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = True
def setup_network(self):
# Must set the blockversion for this test
self.node... | newscript.append(i) | conditional_block |
nulldummy.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
Genera... | (tx):
scriptSig = CScript(tx.vin[0].scriptSig)
newscript = []
for i in scriptSig:
if (len(newscript) == 0):
assert(len(i) == 0)
newscript.append(b'\x51')
else:
newscript.append(i)
tx.vin[0].scriptSig = CScript(newscript)
tx.rehash()
class NULLDUMM... | trueDummy | identifier_name |
nulldummy.py | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
Genera... | self.lastblocktime += 1
self.lastblockheight += 1
else:
assert_equal(node.getbestblockhash(), self.lastblockhash)
if __name__ == '__main__':
NULLDUMMYTest().main() | assert_equal(node.getbestblockhash(), block.hash)
self.tip = block.sha256
self.lastblockhash = block.hash | random_line_split |
series.py | """
series.py
:copyright: (c) 2014-2015 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows how to use **SeriesReader** to get the data in various ways
But you can use them with **Reader** class as well
"""
import os
from pyexcel.ext import ods3
from pyexcel import SeriesReader
fro... | main(os.getcwd()) | conditional_block | |
series.py | """
series.py
:copyright: (c) 2014-2015 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows how to use **SeriesReader** to get the data in various ways
But you can use them with **Reader** class as well
"""
import os
from pyexcel.ext import ods3
from pyexcel import SeriesReader
fro... | # get the content in one dimensional array
# but iterate it vertically
data = to_array(reader.vertical())
print(data)
# [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
# get the content in one dimensional array
# but iterate it vertically in revserse
# order
data = to_array(reade... | reader = SeriesReader(os.path.join(base_dir,"example_series.ods"))
data = to_dict(reader)
print(json.dumps(data))
# output:
# {"Column 2": [4.0, 5.0, 6.0], "Column 3": [7.0, 8.0, 9.0], "Column 1": [1.0, 2.0, 3.0]}
# get the column headers
print(reader.colnames)
# [u'Column 1', u'Column ... | identifier_body |
series.py | """
series.py
:copyright: (c) 2014-2015 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows how to use **SeriesReader** to get the data in various ways
But you can use them with **Reader** class as well
"""
import os
from pyexcel.ext import ods3
from pyexcel import SeriesReader
fro... | reader.filter(EvenColumnFilter())
data = to_dict(reader)
print(data)
# {u'Column 3': [8.0], u'Column 1': [2.0]}
# and you can write the filtered results
# into a file
w = Writer("example_series_filter.xls")
w.write_reader(reader)
w.close()
if __name__ == '__main__':
main(o... | reader.filter(OddRowFilter()) | random_line_split |
series.py | """
series.py
:copyright: (c) 2014-2015 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows how to use **SeriesReader** to get the data in various ways
But you can use them with **Reader** class as well
"""
import os
from pyexcel.ext import ods3
from pyexcel import SeriesReader
fro... | (base_dir):
# print all in json
#
# Column 1 Column 2 Column 3
# 1 4 7
# 2 5 8
# 3 6 9
reader = SeriesReader(os.path.join(base_dir,"example_series.ods"))
data = to_dict(reader)
print(json.dumps(data))
# output:
# {"Column 2": [4.0, 5.... | main | identifier_name |
twq.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
func... | (n: number): number {
return 5;
}
export default [
'twq',
[['Subbaahi', 'Zaarikay b'], u, u],
u,
[
['H', 'T', 'T', 'L', 'L', 'L', 'S'], ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'],
['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamiisa', 'Alzuma', 'Asibti'],
['Alh', 'Ati', 'Ata', 'Ala', 'Alm... | plural | identifier_name |
twq.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
func... |
export default [
'twq',
[['Subbaahi', 'Zaarikay b'], u, u],
u,
[
['H', 'T', 'T', 'L', 'L', 'L', 'S'], ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'],
['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamiisa', 'Alzuma', 'Asibti'],
['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi']
],
u,
[
... | {
return 5;
} | identifier_body |
twq.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
func... | ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi']
],
u,
[
['Ž', 'F', 'M', 'A', 'M', 'Ž', 'Ž', 'U', 'S', 'O', 'N', 'D'],
['Žan', 'Fee', 'Mar', 'Awi', 'Me', 'Žuw', 'Žuy', 'Ut', 'Sek', 'Okt', 'Noo', 'Dee'],
[
'Žanwiye', 'Feewiriye', 'Marsi', 'Awiril', 'Me', 'Žuweŋ', 'Žuyye', 'Ut', 'Sektanbur',
... | u,
[
['H', 'T', 'T', 'L', 'L', 'L', 'S'], ['Alh', 'Ati', 'Ata', 'Ala', 'Alm', 'Alz', 'Asi'],
['Alhadi', 'Atinni', 'Atalaata', 'Alarba', 'Alhamiisa', 'Alzuma', 'Asibti'], | random_line_split |
material_data_parser.py | import os
import numpy
__author__ = 'Milan'
class NewXS(Exception):
pass
# noinspection PyUnboundLocalVariable
def | (data_file_name):
xs = ''
new_xs = ''
xs_data = dict()
data_buffer = []
xs_names = \
{
'St': 'St',
'Ss': 'Ss',
'nSf': 'nSf',
'chi': 'chi',
'Q': 'Q'
}
with open(data_file_name, 'r') as f:
lines = f.readlines()
for li, line in enumerate(lines):
# Skip comment... | parse_material | identifier_name |
material_data_parser.py | import os
import numpy
__author__ = 'Milan'
class NewXS(Exception):
|
# noinspection PyUnboundLocalVariable
def parse_material(data_file_name):
xs = ''
new_xs = ''
xs_data = dict()
data_buffer = []
xs_names = \
{
'St': 'St',
'Ss': 'Ss',
'nSf': 'nSf',
'chi': 'chi',
'Q': 'Q'
}
with open(data_file_name, 'r') as f:
lines = f.readlines... | pass | identifier_body |
material_data_parser.py | import os
import numpy
__author__ = 'Milan'
class NewXS(Exception):
pass
# noinspection PyUnboundLocalVariable
def parse_material(data_file_name):
xs = ''
new_xs = ''
xs_data = dict()
data_buffer = []
xs_names = \
{
'St': 'St',
'Ss': 'Ss',
'nSf': 'nSf',
'chi': 'chi',
'Q... | data_array = numpy.atleast_1d(numpy.array(data_buffer).squeeze())
# Assert consistency of xs data (or set the number of groups for the first time)
try:
assert data_array.shape[0] == G
except NameError:
G = data_array.shape[0]
if xs == 'Ss':
data_ar... | if line.startswith(('*','\n')):
continue
try:
new_xs = xs_names[line.strip()]
except KeyError:
# look for new data
data = line.replace(',', ' ').replace(';', ' ').split()
try:
data_buffer.append(map(float, data))
except ValueError:
# TODO: Unexpected data er... | conditional_block |
material_data_parser.py | import os
import numpy
__author__ = 'Milan'
class NewXS(Exception):
pass
# noinspection PyUnboundLocalVariable
def parse_material(data_file_name):
xs = ''
new_xs = ''
xs_data = dict()
data_buffer = []
xs_names = \
{
'St': 'St',
'Ss': 'Ss',
'nSf': 'nSf',
'chi': 'chi',
'Q... |
try:
new_xs = xs_names[line.strip()]
except KeyError:
# look for new data
data = line.replace(',', ' ').replace(';', ' ').split()
try:
data_buffer.append(map(float, data))
except ValueError:
# TODO: Unexpected data error
raise
if new_xs != xs or li ==... |
for li, line in enumerate(lines):
# Skip comments and empty lines
if line.startswith(('*','\n')):
continue | random_line_split |
backbone.babysitter.js | // Backbone.BabySitter
// -------------------
// v0.0.5
//
// Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
// Distributed under MIT license
//
// http://github.com/babysitterjs/backbone.babysitter
// Backbone.ChildViewContainer
// ---------------------------
//
// Provide a container to store, retrieve and
/... | // update the length
this._updateLength();
},
// Call a method on every view in the container,
// passing parameters to the call method one at a
// time, like `function.call`.
call: function(method, args){
args = Array.prototype.slice.call(arguments, 1);
this.apply(method, a... | random_line_split | |
backbone.babysitter.js | // Backbone.BabySitter
// -------------------
// v0.0.5
//
// Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
// Distributed under MIT license
//
// http://github.com/babysitterjs/backbone.babysitter
// Backbone.ChildViewContainer
// ---------------------------
//
// Provide a container to store, retrieve and
/... |
// delete collection index
if (view.collection){
delete this._indexByCollection[view.collection.cid];
}
// delete custom index
var cust;
for (var key in this._indexByCustom){
if (this._indexByCustom.hasOwnProperty(key)){
if (this._indexByCustom[key] === ... | {
delete this._indexByModel[view.model.cid];
} | conditional_block |
toHaveHTML--tests.js | const { shallow, mount } = require('enzyme');
const React = require('react');
function Fixture() |
describe('toHaveHTML', () => {
it('works with `shallow` renders', () => {
const wrapper = shallow(<Fixture />);
expect(wrapper.find('#child')).toHaveHTML(
'<span id="child">Test</span>'
);
});
it('works with `mount` renders', () => {
const wrapper = mount(<Fixture />);
expect(wrapper.... | {
return (
<div id="root">
<span id="child">Test</span>
</div>
);
} | identifier_body |
toHaveHTML--tests.js | const { shallow, mount } = require('enzyme');
const React = require('react');
function Fixture() {
return (
<div id="root">
<span id="child">Test</span>
</div>
);
}
describe('toHaveHTML', () => {
it('works with `shallow` renders', () => {
const wrapper = shallow(<Fixture />);
expect(wrappe... | }); | expect(wrapper.find('#child')).not.toHaveHTML('foo');
}); | random_line_split |
toHaveHTML--tests.js | const { shallow, mount } = require('enzyme');
const React = require('react');
function | () {
return (
<div id="root">
<span id="child">Test</span>
</div>
);
}
describe('toHaveHTML', () => {
it('works with `shallow` renders', () => {
const wrapper = shallow(<Fixture />);
expect(wrapper.find('#child')).toHaveHTML(
'<span id="child">Test</span>'
);
});
it('works wi... | Fixture | identifier_name |
exceptions.py | """
Global Django exception and warning classes.
"""
class DjangoRuntimeWarning(RuntimeWarning):
pass
class ObjectDoesNotExist(Exception):
"The requested object does not exist"
silent_variable_failure = True
class MultipleObjectsReturned(Exception):
"The query returned multiple objects when only one w... | (Exception):
"The user did not have permission to do that"
pass
class ViewDoesNotExist(Exception):
"The requested view does not exist"
pass
class MiddlewareNotUsed(Exception):
"This middleware is not used in this server configuration"
pass
class ImproperlyConfigured(Exception):
"Django is... | PermissionDenied | identifier_name |
exceptions.py | """
Global Django exception and warning classes.
"""
class DjangoRuntimeWarning(RuntimeWarning):
pass
class ObjectDoesNotExist(Exception):
"The requested object does not exist"
silent_variable_failure = True
class MultipleObjectsReturned(Exception):
"The query returned multiple objects when only one w... |
class MiddlewareNotUsed(Exception):
"This middleware is not used in this server configuration"
pass
class ImproperlyConfigured(Exception):
"Django is somehow improperly configured"
pass
class FieldError(Exception):
"""Some kind of problem with a model field."""
pass
NON_FIELD_ERRORS = '__al... | "The requested view does not exist"
pass | identifier_body |
exceptions.py | """
Global Django exception and warning classes.
"""
class DjangoRuntimeWarning(RuntimeWarning):
pass
class ObjectDoesNotExist(Exception):
"The requested object does not exist"
silent_variable_failure = True
class MultipleObjectsReturned(Exception):
"The query returned multiple objects when only one w... |
return error_dict
| error_dict[NON_FIELD_ERRORS] = self.messages | conditional_block |
exceptions.py | """
Global Django exception and warning classes.
"""
class DjangoRuntimeWarning(RuntimeWarning):
pass
class ObjectDoesNotExist(Exception):
"The requested object does not exist"
silent_variable_failure = True
class MultipleObjectsReturned(Exception):
"The query returned multiple objects when only one w... |
class ViewDoesNotExist(Exception):
"The requested view does not exist"
pass
class MiddlewareNotUsed(Exception):
"This middleware is not used in this server configuration"
pass
class ImproperlyConfigured(Exception):
"Django is somehow improperly configured"
pass
class FieldError(Exception):
... | "The user did not have permission to do that"
pass | random_line_split |
match.js | "use strict";
var valueToString = require("@sinonjs/commons").valueToString;
var indexOf = require("@sinonjs/commons").prototypes.string.indexOf;
var forEach = require("@sinonjs/commons").prototypes.array.forEach;
var type = require("type-detect");
var engineCanCompareMaps = typeof Array.from === "function";
var deep... |
/* eslint-disable complexity */
/**
* Matches an object with a matcher (or value)
*
* @alias module:samsam.match
* @param {object} object The object candidate to match
* @param {object} matcherOrValue A matcher or value to match against
* @returns {boolean} true when `object` matches `matcherOrValue`
*/
functi... | {
if (subset.length === 0) {
return true;
}
var i, l, j, k;
for (i = 0, l = array.length; i < l; ++i) {
if (compare(array[i], subset[0])) {
for (j = 0, k = subset.length; j < k; ++j) {
if (i + j >= l) {
return false;
}
... | identifier_body |
match.js | "use strict";
var valueToString = require("@sinonjs/commons").valueToString;
var indexOf = require("@sinonjs/commons").prototypes.string.indexOf;
var forEach = require("@sinonjs/commons").prototypes.array.forEach;
var type = require("type-detect");
var engineCanCompareMaps = typeof Array.from === "function";
var deep... | (array, subset, compare) {
if (subset.length === 0) {
return true;
}
var i, l, j, k;
for (i = 0, l = array.length; i < l; ++i) {
if (compare(array[i], subset[0])) {
for (j = 0, k = subset.length; j < k; ++j) {
if (i + j >= l) {
return false... | arrayContains | identifier_name |
match.js | "use strict";
var valueToString = require("@sinonjs/commons").valueToString;
var indexOf = require("@sinonjs/commons").prototypes.string.indexOf;
var forEach = require("@sinonjs/commons").prototypes.array.forEach;
var type = require("type-detect");
var engineCanCompareMaps = typeof Array.from === "function";
var deep... |
/* istanbul ignore next: this is basically the rest of the function, which is covered */
break;
case "Array":
case "Int8Array":
case "Uint8Array":
case "Uint8ClampedArray":
case "Int16Array":
case "Uint16Array":
case "Int32Array":
... | {
return object.getTime() === matcherOrValue.getTime();
} | conditional_block |
match.js | "use strict";
var valueToString = require("@sinonjs/commons").valueToString;
var indexOf = require("@sinonjs/commons").prototypes.string.indexOf;
var forEach = require("@sinonjs/commons").prototypes.array.forEach;
var type = require("type-detect");
var engineCanCompareMaps = typeof Array.from === "function";
var deep... | }
switch (type(object)) {
case "null":
return false;
case "Set":
return isSubset(matcherOrValue, object, match);
default:
break;
}
/* istanbul ignore else */
if (matcherOrValue && typeof matcherOrValue === "object") {
if (matcherO... | default:
break; | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-08 09:18
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import tinymce.models
|
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=... | class Migration(migrations.Migration): | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-08 09:18
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import tinymce.models
class | (migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serial... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-08 09:18
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import tinymce.models
class Migration(migrations.Migration):
| ('description', tinymce.models.HTMLField()),
],
),
migrations.CreateModel(
name='Thread',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharFi... | initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')... | identifier_body |
Zips.ts | import {PutIoHelper} from '../helpers/PutIoHelper';
export class | extends PutIoHelper {
/**
*
* Creates zip file for given files. A zip_id is returned to keep track of the status of zip creation process.
*
* @param fileIds: Array of file ids. Ex: [1,2,3,4]
*/
public createZip(fileIds: number[]): Promise<string> {
const paramaters: string[]... | Zips | identifier_name |
Zips.ts | import {PutIoHelper} from '../helpers/PutIoHelper';
export class Zips extends PutIoHelper {
/**
*
* Creates zip file for given files. A zip_id is returned to keep track of the status of zip creation process.
*
* @param fileIds: Array of file ids. Ex: [1,2,3,4]
*/
public createZip(fi... |
/**
*
* Gives detailed information about the give zip file id. Check the zip creation process status with your zip_id.
* When the process is done, you will get url value along with size and missing_files.
* You might need to poll this end point until you get an url value. missing_files is an ... | {
return this.requestData('GET', 'zips/list', []);
} | identifier_body |
Zips.ts | import {PutIoHelper} from '../helpers/PutIoHelper';
export class Zips extends PutIoHelper {
/**
*
* Creates zip file for given files. A zip_id is returned to keep track of the status of zip creation process.
*
* @param fileIds: Array of file ids. Ex: [1,2,3,4]
*/
public createZip(fi... | }
/**
*
* Lists active zip files.
*/
public getZipsList(): Promise<string> {
return this.requestData('GET', 'zips/list', []);
}
/**
*
* Gives detailed information about the give zip file id. Check the zip creation process status with your zip_id.
* When the ... | };
paramaters.push(JSON.stringify(transferIdsToCancel));
return this.requestData('POST', 'zips/create', paramaters); | random_line_split |
rdio.py | import urllib.request, urllib.parse, urllib.error
from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.backends import Consum... |
def get_user_details(self, response):
return {
'username': response['username'],
'first_name': response['firstName'],
'last_name': response['lastName'],
'fullname': response['displayName'],
}
class RdioOAuth1Backend(RdioBaseBackend):
"""Rdio OA... | return response['key'] | identifier_body |
rdio.py | import urllib.request, urllib.parse, urllib.error
from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.backends import Consum... | if token and 'access_token' in token:
token = dict(tok.split('=')
for tok in token['access_token'].split('&'))
return token
class RdioOAuth2Backend(RdioBaseBackend):
name = 'rdio-oauth2'
EXTRA_DATA = [
('key', 'rdio_id'),
('icon', 'rdio_i... | ]
@classmethod
def tokens(cls, instance):
token = super(RdioOAuth1Backend, cls).tokens(instance) | random_line_split |
rdio.py | import urllib.request, urllib.parse, urllib.error
from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.backends import Consum... | (self, token, url, params):
"""Generate OAuth request, setups callback url"""
if 'oauth_verifier' in self.data:
params['oauth_verifier'] = self.data['oauth_verifier']
request = OAuthRequest.from_consumer_and_token(self.consumer,
... | oauth_post_request | identifier_name |
rdio.py | import urllib.request, urllib.parse, urllib.error
from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.backends import Consum... |
return token
class RdioOAuth2Backend(RdioBaseBackend):
name = 'rdio-oauth2'
EXTRA_DATA = [
('key', 'rdio_id'),
('icon', 'rdio_icon_url'),
('url', 'rdio_profile_url'),
('username', 'rdio_username'),
('streamRegion', 'rdio_stream_region'),
('refresh_token... | token = dict(tok.split('=')
for tok in token['access_token'].split('&')) | conditional_block |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import models
from django.apps import apps
from empresa.models import Empresa
import json
import os
import tempfile
import datetime
import requests
class Parking(models.Model):
empresa = models.OneToOneField(Empresa)
... |
else:
r = requests.get(self.abresiempre_url)
return r.status_code == 200
def cierra(self):
if self.cierra_post:
r = requests.post(self.cierra_url, data=json.loads(self.cierra_post))
else:
r = requests.get(self.cierra_url)
return r.status_... | r = requests.post(self.abresiempre_url, data=json.loads(self.abresiempre_post)) | conditional_block |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import models
from django.apps import apps
from empresa.models import Empresa
import json
import os
import tempfile
import datetime
import requests
class Parking(models.Model):
empresa = models.OneToOneField(Empresa)
... | ordering = ('hora', )
class NodoRemoto(models.Model):
parking = models.ForeignKey(Parking)
host_name = models.CharField(max_length = 100, blank = True, null = True, help_text = 'Nombre del Host')
url = models.CharField(max_length = 100, blank=True, null=True, help_text = ' url del demonio nameko' ... | ta:
| identifier_name |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import models
from django.apps import apps
from empresa.models import Empresa
import json
import os
import tempfile
import datetime
import requests
class Parking(models.Model):
empresa = models.OneToOneField(Empresa)
... | cierra_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo")
cierra_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json")
def abre(self):
if self.abre_post:
r = requests.post(self.abre_url,... | random_line_split | |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import models
from django.apps import apps
from empresa.models import Empresa
import json
import os
import tempfile
import datetime
import requests
class Parking(models.Model):
empresa = models.OneToOneField(Empresa)
... | def __str__(self):
return self.descripcion
class Meta:
verbose_name_plural = 'Visores'
| prte_str = "{:.2f}".format(importe)
# print("importe " + imprte_str)
try:
r = requests.post(self.url, json={"importe": importe})
except:
return False
r = requests.post(self.url, json={"importe": importe})
return r.status_code == 200
| identifier_body |
sms_manager.js | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
erpnext.SMSManager = function SMSManager(doc) {
var me = this;
this.setup = function() {
var default_msg = {
'Lead' : '',
'Opportunity' : 'Your enquiry has been logged into th... | this.setup();
} | random_line_split | |
sms_manager.js | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
erpnext.SMSManager = function SMSManager(doc) {
var me = this;
this.setup = function() {
var default_msg = {
'Lead' : '',
'Opportunity' : 'Your enquiry has been logged into th... | else {
me.show_dialog();
}
}
this.show_dialog = function() {
if(!me.dialog)
me.make_dialog();
me.dialog.set_values({
'message': me.message,
'number': me.number
})
me.dialog.show();
}
this.make_dialog = function() {
var d = new frappe.ui.Dialog({
title: 'Send SMS',
width: 400,
field... | {
this.get_contact_number(contact, ref_doctype, ref_name)
} | conditional_block |
settings_base.py | """private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.settings_base import CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING
from .. import splitstrip
import private_base as private
ENGAGE_ROBOTS = False
EMAIL_BACKEND = 'django.core.m... |
PERF_TEST_URL = 'http://talos-addon-master1.amotest.scl1.mozilla.com/trigger/trigger.cgi'
REDIRECT_URL = 'https://outgoing.allizom.org/v1/'
CLEANCSS_BIN = 'cleancss'
UGLIFY_BIN = 'uglifyjs'
CELERYD_TASK_SOFT_TIME_LIMIT = 240
LESS_PREPROCESS = True
XSENDFILE_HEADER = 'X-Accel-Redirect'
ALLOW_SELF_REVIEWS = True
... | ]
NEW_FEATURES = True | random_line_split |
test_exec2_enums_rand_cut.py | = True
CUT_EXPR_CNT = 200
ROWS=1000000
DO_PLOT = getpass.getuser()=='kevin'
DO_MEDIAN = True
MAX_QBINS = 1000
MULTI_PASS = 1
def | (n, randChars=randChars, quoteChars=quoteChars):
# randomly return None 10% of the time
# if random.randint(0,9)==0:
# return 'huh' # empty string doesn't work for exec compare?
choiceStr = randChars + quoteChars
mightBeNumberOrWhite = True
while mightBeNumberOrWhite:
# H2O doesn't s... | random_enum | identifier_name |
test_exec2_enums_rand_cut.py | = True
CUT_EXPR_CNT = 200
ROWS=1000000
DO_PLOT = getpass.getuser()=='kevin'
DO_MEDIAN = True
MAX_QBINS = 1000
MULTI_PASS = 1
def random_enum(n, randChars=randChars, quoteChars=quoteChars):
# randomly return None 10% of the time
# if random.randint(0,9)==0:
# return 'huh' # empty string doesn't work ... |
@classmethod
def setUpClass(cls):
global SEED, localhost
SEED = h2o.setup_random_seed()
localhost = h2o.decide_if_localhost()
if (localhost):
h2o.build_cloud(1,java_heap_GB=14)
else:
h2o_hosts.build_cloud_with_hosts()
@classmethod
def te... | h2o.check_sandbox_for_errors() | identifier_body |
test_exec2_enums_rand_cut.py | = True
CUT_EXPR_CNT = 200
ROWS=1000000
DO_PLOT = getpass.getuser()=='kevin'
DO_MEDIAN = True
MAX_QBINS = 1000
MULTI_PASS = 1
def random_enum(n, randChars=randChars, quoteChars=quoteChars):
# randomly return None 10% of the time
# if random.randint(0,9)==0:
# return 'huh' # empty string doesn't work ... |
cutExpr = ' && '.join(cutExprList)
print "cutExpr:", cutExpr
# should be two different keys in the sample
e = random.sample(eKeys,2)
fKey = e[0]
eKey = e[1]
rowExpr = '%s[%s,];' % (hex_key, cutExpr)
... | if c is None:
continue
else:
# new ...ability to reference cols
# src[ src$age<17 && src$zip=95120 && ... , ]
cutExprList.append('p$C'+str(i+1)+'=='+c) | conditional_block |
test_exec2_enums_rand_cut.py | _LENGTH = True
CUT_EXPR_CNT = 200
ROWS=1000000
DO_PLOT = getpass.getuser()=='kevin'
DO_MEDIAN = True
MAX_QBINS = 1000
MULTI_PASS = 1
def random_enum(n, randChars=randChars, quoteChars=quoteChars):
# randomly return None 10% of the time
# if random.randint(0,9)==0:
# return 'huh' # empty string doesn'... | cutExprList = []
for i,c in enumerate(cutValue):
if c is None:
continue
else:
# new ...ability to reference cols
# src[ src$age<17 && src$zip=95120 && ... , ]
... | celChoice = str(random.choice(range(len(cel))))
else:
celChoice = random.choice(cel)
cutValue[c] = celChoice
| random_line_split |
midi_output.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | (self, str_message):
self.send(mido.parse_string(str_message))
def send(self, message):
self._port.send(message)
def open(self):
port_name = mido_port_name(self._port_name, 'O')
self._port = mido_backend().open_output(port_name)
| send_from_str | identifier_name |
midi_output.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | def __init__(self, port_name='AppDefault'):
super().__init__(port_name=port_name)
def send_from_str(self, str_message):
self.send(mido.parse_string(str_message))
def send(self, message):
self._port.send(message)
def open(self):
port_name = mido_port_name(self._port_name, '... | identifier_body | |
midi_output.py | # -*- coding: utf-8 -*-
#
# This file is part of Linux Show Player
#
# Copyright 2012-2016 Francesco Ceruti <ceppofrancy@gmail.com>
#
# Linux Show Player 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 ... | def open(self):
port_name = mido_port_name(self._port_name, 'O')
self._port = mido_backend().open_output(port_name) | self._port.send(message)
| random_line_split |
tessellation.rs | #[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn main() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building th... |
glium::VertexBuffer::new(&display,
vec![
Vertex { position: [-0.5, -0.5] },
Vertex { position: [ 0.0, 0.5] },
Vertex { position: [ 0.5, -0.5] },
]
)
};
// building the index buffer
let index_buffer = glium::IndexBuff... | struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position); | random_line_split |
tessellation.rs | #[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn main() {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building th... | ,
_ => ()
}
}
support::Action::Continue
});
}
| {
if tess_level >= 2 {
tess_level -= 1;
println!("New tessellation level: {}", tess_level);
}
} | conditional_block |
tessellation.rs | #[macro_use]
extern crate glium;
use glium::Surface;
use glium::glutin;
use glium::index::PrimitiveType;
mod support;
fn | () {
use glium::DisplayBuild;
// building the display, ie. the main object
let display = glutin::WindowBuilder::new()
.build_glium()
.unwrap();
// building the vertex buffer, which contains all the vertices that we will draw
let vertex_buffer = {
#[derive(Copy, Clone)]
... | main | identifier_name |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice; |
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-access-numeric-constants-using-the-float-trait
pub trait Castd {
fn d(self: &Self) -> f64;
}
impl Castd for f32 {
fn d(self: &Self) ->... | use self::num::Float;
// use std::ops;
use std::f32;
use std::f64; | random_line_split |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-acce... |
}
self
}
}
// **********************************************
// pub fn sinc2(y: &mut f64) -> &mut f64 {
// if *y != 0f64 {
// *y = (*y*f64::consts::PI).sin()/(*y*f64::pi());
// } else {
// *y = 1f64;
// }
// y
// }
//
// pub fn sinc(y: &mut [f64]) -> &mut [f64] {... | {
*yi = 1f64;
} | conditional_block |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-acce... |
}
pub trait FloatConst {
fn pi() -> Self;
}
impl FloatConst for f32 {
fn pi() -> Self { f32::consts::PI }
}
impl FloatConst for f64 {
fn pi() -> Self { f64::consts::PI }
}
pub fn linspace_vec<'a, T: 'a>(start: T, stop: T, len: usize) ->
Vec<T>
where T: Float {
let zero: T = T::zero();
let... | {*self as f64} | identifier_body |
utils.rs | extern crate num;
extern crate alloc;
extern crate rgsl;
use heapslice;
use self::num::Float;
// use std::ops;
use std::f32;
use std::f64;
// you can't do std::<T>::consts::PI. Workaround (needed e.g. for sinc())
// https://github.com/rust-lang/rfcs/pull/1062
// http://stackoverflow.com/questions/32763783/how-to-acce... | (self) -> Self {
for yi in (*self).iter_mut() {
if *yi != 0f64 {
*yi = (*yi*f64::consts::PI).sin()/(*yi*f64::consts::PI);
} else {
*yi = 1f64;
}
}
self
}
}
// **********************************************
// pub fn sinc... | sinc | identifier_name |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... |
problem!("142857", solve);
| {
compute().to_string()
} | identifier_body |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... | return n
}
}
fn solve() -> String {
compute().to_string()
}
problem!("142857", solve); | if ds != (n * 6).into_digit_histogram() { continue }
| random_line_split |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... | () -> String {
compute().to_string()
}
problem!("142857", solve);
| solve | identifier_name |
p052.rs | //! [Problem 52](https://projecteuler.net/problem=52) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
use integer::Integer;
fn compute() -> u32 {
let radix = 1... |
if ds != (n * 5).into_digit_histogram() { continue }
if ds != (n * 6).into_digit_histogram() { continue }
return n
}
}
fn solve() -> String {
compute().to_string()
}
problem!("142857", solve);
| { continue } | conditional_block |
x86_32_pymsasid.py | # ScratchABit - interactive disassembler
#
# Copyright (c) 2015-2018 Paul Sokolovsky
#
# 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 ... | return _x86_pymsasid.X86Processor(bitness=32) | identifier_body | |
x86_32_pymsasid.py | # ScratchABit - interactive disassembler | #
# Copyright (c) 2015-2018 Paul Sokolovsky
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distri... | random_line_split | |
x86_32_pymsasid.py | # ScratchABit - interactive disassembler
#
# Copyright (c) 2015-2018 Paul Sokolovsky
#
# 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 ... | ():
return _x86_pymsasid.X86Processor(bitness=32)
| PROCESSOR_ENTRY | identifier_name |
cdn.rs | use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
... | let data = load_from_stream(&mut response);
let file = self.cache_dir.clone() + path;
fs::create_dir_all(path::Path::new(file.as_str()).parent().unwrap()).unwrap();
let mut f = fs::File::create(file).unwrap();
write_to_stream(&mut f, &mime, &data);
return Some((mime, data));
}
}
impl res... | {
let url = self.prefix.clone() + path;
let mut response = match self.client.get(&url).send() {
Ok(r) => r, _ => return None
};
if response.status != hyper::status::StatusCode::Ok {
return None;
}
let mime = resource_loaders::path_to_mime(path).map(|x| x.to_owned()).unwrap_or_else... | identifier_body |
cdn.rs | use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
... |
let mut f = match fs::File::open(file) {
Ok(f) => io::BufReader::new(f), _ => return None
};
let mut mime = String::new();
f.read_line(&mut mime).unwrap();
return Some((mime.trim().to_owned(), load_from_stream(&mut f)));
}
fn load_from_cdn(&self, path: &str) -> Option<(String, Vec<u8>)... | fn load_from_cache(&self, path: &str) -> Option<(String, Vec<u8>)> {
let file = self.cache_dir.clone() + path; | random_line_split |
cdn.rs | use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use hyper;
use resource_loaders;
pub struct Loader {
prefix: String,
cache_dir: String,
client: hyper::Client
}
impl Loader {
pub fn new(prefix: &str, cache_dir: &str) -> Loader {
fs::create_dir_all(cache_dir).unwrap();
... | (write: &mut Write, mime: &String, data: &Vec<u8>) {
write.write_all(format!("{}\n", mime).as_bytes()).unwrap();
write.write_all(data.as_slice()).unwrap();
}
| write_to_stream | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.