file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
tables.js | import DB from '../db';
import * as types from '../constants/tablesConstants';
import { stopFetching, internalInitTable } from './currentTable';
export function setCurrentTable(tableName) {
return {
type: types.SET_CURRENT_TABLE,
tableName
};
}
export function changeTableName(newTableName) {
return {
... |
DB.getTables()
.then(
(tables) => {
if (tables.length) {
return DB.getTableOid(tables);
}
return tables;
},
(error) => {
reject(error);
}
)
.then(
(tables) => {
if (tables.length) {
r... | {
dispatch({ type: types.GET_TABLES, tables: [] });
} | conditional_block |
tables.js | import DB from '../db';
import * as types from '../constants/tablesConstants';
import { stopFetching, internalInitTable } from './currentTable';
export function | (tableName) {
return {
type: types.SET_CURRENT_TABLE,
tableName
};
}
export function changeTableName(newTableName) {
return {
type: types.CHANGE_TABLE_NAME,
newTableName
};
}
export function createTable(tableName, i = -1) {
return dispatch => new Promise((resolve, reject) => {
// eslint-... | setCurrentTable | identifier_name |
manager.py | import os
import stepper
import time
import random
import thermo
import threading
import traceback
import logging
import states
import PID
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class TempLog(object):
def __init__(self, history, interval=60, suffix=""): #save data every 60 seconds
impo... |
@property
def completed(self):
return self.elapsed > self.schedule[-1][0]
def stop(self):
self.running = False
def run(self):
_next = time.time()+self.interval
while not self.completed and self.running:
ts = self.elapsed
#find epoch
for i in range(len(self.schedule)-1):
if self.schedule[i][... | ''' Returns the elapsed time from start in seconds'''
return time.time() - self.start_time | identifier_body |
manager.py | import os
import stepper
import time
import random
import thermo
import threading
import traceback
import logging
import states
import PID
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class TempLog(object):
def __init__(self, history, interval=60, suffix=""): #save data every 60 seconds
impo... | self.schedule = schedule
self.therm = therm
self.regulator = regulator
self.interval = interval
self.start_time = start_time
if start_time is None:
self.start_time = time.time()
self.pid = PID.PID(Kp, Ki, Kd)
self.callback = callback
self.running = True
self.duty_cycle = False
self.start()
@... | Kp=.03, Ki=.015, Kd=.001):
super(Profile, self).__init__()
self.daemon = True
| random_line_split |
manager.py | import os
import stepper
import time
import random
import thermo
import threading
import traceback
import logging
import states
import PID
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class TempLog(object):
def __init__(self, history, interval=60, suffix=""): #save data every 60 seconds
impo... |
self.fname = os.path.join(paths.log_path, fname+suffix+".log")
with open(self.fname, 'w') as fp:
fp.write("time\ttemp\n")
for t, temp in history:
fp.write("%f\t%f\n"%(t, temp))
self.next = time.time() + interval
self.interval = interval
self._buffer = []
def __iter__(self):
return iter(self.his... | suffix = "_"+suffix | conditional_block |
manager.py | import os
import stepper
import time
import random
import thermo
import threading
import traceback
import logging
import states
import PID
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class TempLog(object):
def __init__(self, history, interval=60, suffix=""): #save data every 60 seconds
impo... | (self, start=states.Idle, simulate=False):
"""
Implement a state machine that cycles through States
"""
super(Manager, self).__init__()
self._send = None
if simulate:
self.regulator = stepper.Regulator(simulate=simulate)
self.therm = thermo.Simulate(regulator=self.regulator)
else:
self.regulat... | __init__ | identifier_name |
msgsend-pipes.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 ... |
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = args[1].parse::<usize>().unwrap();
let workers = args[2].parse::<usize>().unwrap();
let num_bytes = 100;
let mut result = None;
let mut to_parent = Some(to_parent);
let dur = Duration::span(|| {
let to_p... | {
let mut count: usize = 0;
let mut done = false;
while !done {
match requests.recv() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
count += b;
}
Er... | identifier_body |
msgsend-pipes.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 ... | //
// I *think* it's the same, more or less.
#![feature(std_misc)]
use std::sync::mpsc::{channel, Sender, Receiver};
use std::env;
use std::thread;
use std::time::Duration;
enum request {
get_count,
bytes(usize),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<usize>) {
let mut cou... | //
// http://github.com/PaulKeeble/ScalaVErlangAgents | random_line_split |
msgsend-pipes.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 ... | (requests: &Receiver<request>, responses: &Sender<usize>) {
let mut count: usize = 0;
let mut done = false;
while !done {
match requests.recv() {
Ok(request::get_count) => { responses.send(count.clone()); }
Ok(request::bytes(b)) => {
//println!("server: received {} by... | server | identifier_name |
mod.rs | // Copyright (c) 2019, Ben Boeckel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of cond... | // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
... | // may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | random_line_split |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... |
#[cfg(not(target_os = "macos"))]
pub fn utime_now() -> c_long {
libc::UTIME_NOW
}
#[cfg(target_os = "macos")]
pub fn utime_now() -> c_long {
-1
}
#[cfg(not(target_os = "macos"))]
pub fn utime_omit() -> c_long {
libc::UTIME_OMIT
}
#[cfg(target_os = "macos")]
pub fn utime_omit() -> c_long {
-2
}
| {
use nix::errno::Errno;
use nix::fcntl::{openat, readlinkat, OFlag};
use nix::sys::stat::Mode;
const MAX_SYMLINK_EXPANSIONS: usize = 128;
/// close all the intermediate file descriptors, but make sure not to drop either the original
/// dirfd or the one we return (which may be the same dirfd)... | identifier_body |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... | () -> c_long {
-1
}
#[cfg(not(target_os = "macos"))]
pub fn utime_omit() -> c_long {
libc::UTIME_OMIT
}
#[cfg(target_os = "macos")]
pub fn utime_omit() -> c_long {
-2
}
| utime_now | identifier_name |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... |
// not a symlink, so we're done;
return Ok((
ret_dir_success(&mut dir_stack),
OsStr::from_bytes(component).to_os_string(),
));
}
}
if path_stack.is_empty() {
// no further components to proc... | random_line_split | |
fs_helpers.rs | #![allow(non_camel_case_types)]
#![allow(unused_unsafe)]
use crate::ctx::WasiCtx;
use crate::host;
use lucet_runtime::vmctx::Vmctx;
use nix::libc::{self, c_long};
use std::ffi::{OsStr, OsString};
use std::os::unix::prelude::{OsStrExt, OsStringExt, RawFd};
#[cfg(target_os = "linux")]
pub const O_RSYNC: nix::fcntl::OF... |
Err(e)
// Check to see if it was a symlink. Linux indicates
// this with ENOTDIR because of the O_DIRECTORY flag.
if e.as_errno() == Some(Errno::ELOOP)
|| e.as_errno() == Some(Errno::EMLINK)
... | {
dir_stack.push(new_dir);
continue;
} | conditional_block |
tydecode.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 ... | (st: @mut PState, is_last: @fn(char) -> bool) ->
ast::ident {
let rslt = scan(st, is_last, str::from_bytes);
return st.tcx.sess.ident_of(rslt);
}
pub fn parse_state_from_data(data: @~[u8], crate_num: int,
pos: uint, tcx: ty::ctxt) -> @mut PState {
@mut PState {
data:... | parse_ident_ | identifier_name |
tydecode.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 parse_arg_data(data: @~[u8], crate_num: int, pos: uint, tcx: ty::ctxt,
conv: conv_did) -> ty::arg {
let st = parse_state_from_data(data, crate_num, pos, tcx);
parse_arg(st, conv)
}
fn parse_path(st: @mut PState) -> @ast::path {
let mut idents: ~[ast::ident] = ~[];
fn is_l... | {
let st = parse_state_from_data(data, crate_num, pos, tcx);
parse_ty(st, conv)
} | identifier_body |
tydecode.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 ... | }
'T' => {
assert!((next(st) == '['));
let mut params = ~[];
while peek(st) != ']' { params.push(parse_ty(st, conv)); }
st.pos = st.pos + 1u;
return ty::mk_tup(st.tcx, params);
}
'f' => {
return ty::mk_closure(st.tcx, parse_closure_ty(st, conv));
... | random_line_split | |
config.js | var Response = require("ringo/webapp/response").Response;
var Request = require("ringo/webapp/request").Request;
var urls = [
[(/^\/(index(.html)?)?/), require("./root/index").app],
//[(/^\/(login)/), require("./root/login").app],
[(/^\/(loginpage)/), require("./root/loginpage").app],
//[(/^\/(maps(\/\... |
exports.middleware = [
slash(),
require("ringo/middleware/gzip").middleware,
require("ringo/middleware/static").middleware({base: module.resolve("static")}),
require("ringo/middleware/error").middleware,
require("ringo/middleware/notfound").middleware
];
exports.app = require("ringo/webapp").hand... | {
return function(app) {
return function(request) {
var response;
var servletRequest = request.env.servletRequest;
var pathInfo = servletRequest.getPathInfo();
if (pathInfo === "/") {
var uri = servletRequest.getRequestURI();
if... | identifier_body |
config.js | var Response = require("ringo/webapp/response").Response;
var Request = require("ringo/webapp/request").Request;
var urls = [
[(/^\/(index(.html)?)?/), require("./root/index").app],
//[(/^\/(login)/), require("./root/login").app],
[(/^\/(loginpage)/), require("./root/loginpage").app],
//[(/^\/(maps(\/\... | for(var i = 0, l = files.length; i < l && i < 1; i++) {
var file = files[i].path;
file = file.substring(applicationsFolder.path.length);
application = file.split('/')[0];
}
if(application) {
var applicationConfig = require('applications/' + application + '/config');
applicationConfig.config(urls... | random_line_split | |
config.js | var Response = require("ringo/webapp/response").Response;
var Request = require("ringo/webapp/request").Request;
var urls = [
[(/^\/(index(.html)?)?/), require("./root/index").app],
//[(/^\/(login)/), require("./root/login").app],
[(/^\/(loginpage)/), require("./root/loginpage").app],
//[(/^\/(maps(\/\... | (config) {
return function(app) {
return function(request) {
var response;
var servletRequest = request.env.servletRequest;
var pathInfo = servletRequest.getPathInfo();
if (pathInfo === "/") {
var uri = servletRequest.getRequestURI();
... | slash | identifier_name |
mock.rs | use std::{
io::{self, Cursor, Read, Write},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
written: Cursor<Vec<u8>>,
received: Cursor<Vec<u8>>,
}
impl ... | (&self) -> &[u8] {
self.received.get_ref()
}
}
impl AsyncRead for MockStream {
fn poll_read(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(self.as_mut().received.read(buf))
}
}
impl AsyncWrite for MockS... | received | identifier_name |
mock.rs | use std::{
io::{self, Cursor, Read, Write},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
written: Cursor<Vec<u8>>,
received: Cursor<Vec<u8>>,
}
impl ... | fn poll_read(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Poll::Ready(self.as_mut().received.read(buf))
}
}
impl AsyncWrite for MockStream {
fn poll_write(
mut self: Pin<&mut Self>,
_: &mut Context<'_>,
... | }
impl AsyncRead for MockStream { | random_line_split |
mock.rs | use std::{
io::{self, Cursor, Read, Write},
pin::Pin,
task::{Context, Poll},
};
use tokio::io::{AsyncRead, AsyncWrite};
/// A fake stream for testing network applications backed by buffers.
#[derive(Clone, Debug)]
pub struct MockStream {
written: Cursor<Vec<u8>>,
received: Cursor<Vec<u8>>,
}
impl ... |
}
| {
Poll::Ready(Ok(()))
} | identifier_body |
AngularFire.js | import Firebase from 'firebase/firebase';
export class AngularFire {
ref: Firebase;
| (ref: Firebase) {
this.ref = ref;
}
asArray() {
return new FirebaseArray(this.ref);
}
}
/*
FirebaseArray
*/
export class FirebaseArray {
ref: Firebase;
error: any;
list: Array;
constructor(ref: Firebase) {
this.ref = ref;
this.list = [];
// listen for changes at the Firebase insta... | constructor | identifier_name |
AngularFire.js | import Firebase from 'firebase/firebase';
export class AngularFire {
ref: Firebase;
constructor(ref: Firebase) {
this.ref = ref;
}
asArray() |
}
/*
FirebaseArray
*/
export class FirebaseArray {
ref: Firebase;
error: any;
list: Array;
constructor(ref: Firebase) {
this.ref = ref;
this.list = [];
// listen for changes at the Firebase instance
this.ref.on('child_added', this.created.bind(this), this.error);
this.ref.on('child_mov... | {
return new FirebaseArray(this.ref);
} | identifier_body |
AngularFire.js | import Firebase from 'firebase/firebase';
export class AngularFire {
ref: Firebase;
constructor(ref: Firebase) {
this.ref = ref;
}
asArray() {
return new FirebaseArray(this.ref);
}
}
/*
FirebaseArray
*/
export class FirebaseArray {
ref: Firebase;
error: any;
list: Array;
constructor(ref: ... |
indexFor(key) {
var record = this.getRecord(key);
return this.list.indexOf(record);
}
getRecord(key) {
return this.list.find((item) => key === item._key);
}
} | random_line_split | |
AngularFire.js | import Firebase from 'firebase/firebase';
export class AngularFire {
ref: Firebase;
constructor(ref: Firebase) {
this.ref = ref;
}
asArray() {
return new FirebaseArray(this.ref);
}
}
/*
FirebaseArray
*/
export class FirebaseArray {
ref: Firebase;
error: any;
list: Array;
constructor(ref: ... |
return item;
}
getChild(recOrIndex: any) {
var item = this.getItem(recOrIndex);
return this.ref.child(item._key);
}
add(rec: any) {
this.ref.push(rec);
}
remove(recOrIndex: any) {
this.getChild(recOrIndex).remove();
}
save(recOrIndex: any) {
var item = this.getItem(recOrInde... | {
item = this.getRecord(recOrIndex);
} | conditional_block |
sync-send-iterators-in-libcore.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 ... |
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
)+
})
}
fn main() {
// for char.rs
all_sync_send!("Я"... | {} | identifier_body |
sync-send-iterators-in-libcore.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 ... | <T>(_: T) where T: Sync {}
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
is_send(y.$iter());
)+
})
}
fn main() {
// for char... | is_sync | identifier_name |
sync-send-iterators-in-libcore.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 ... | // pretty-expanded FIXME #23616
#![feature(collections)]
fn is_sync<T>(_: T) where T: Sync {}
fn is_send<T>(_: T) where T: Send {}
macro_rules! all_sync_send {
($ctor:expr, $($iter:ident),+) => ({
$(
let mut x = $ctor;
is_sync(x.$iter());
let mut y = $ctor;
... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
corpusInfo.py | #!/usr/bin/python3
ci_version="0.10"
# This script is used to retrieve corpus information. It can be run after the parser
# has finished its work. The corpus information is part of the final report.
# Database connection is configured in the server configuration.
# Include custom libs
import sys
sys.path.append( '../... | characters[quote['character']] = quote['text']
movieCharacterCount += 1
# Calculating word counts for every character
wordCounts = {cid: len(txt.split()) for cid,txt in characters.items()}
for char, wc in wordCounts.items():
totalWordCount += wc
characterWordCounts += [wc]
charname = char + " (" + movie... | else: | random_line_split |
corpusInfo.py | #!/usr/bin/python3
ci_version="0.10"
# This script is used to retrieve corpus information. It can be run after the parser
# has finished its work. The corpus information is part of the final report.
# Database connection is configured in the server configuration.
# Include custom libs
import sys
sys.path.append( '../... |
if maxWordCount < wc:
maxWordCount = wc
maxWordCountChar = charname
elif maxWordCount == wc:
maxWordCountChar += ", " + charname
# Adding to total Character Count
characterCount += movieCharacterCount
# Counting Characters per Movie
if minPerMovieCharacterCount > movieCharacterCount:
minPerMovieC... | minWordCountChar += ", " + charname | conditional_block |
cipher.rs | //! Implements the basic XTEA cipher routines as described in the
//! paper (http://en.wikipedia.org/wiki/XTEA). These functions only
//! deal with a single 64-bit block of data at a time.
static NUM_ROUNDS: u32 = 32;
use super::{Key, Block};
/// Encrypts 64 bits of `input` using the `key`.
///
/// # Example:
/// `... | {
let key: Key = [10, 20, 30, 42];
let plaintext: Block = [300, 400];
let ciphertext = encipher(&key, &plaintext);
assert!(plaintext != ciphertext);
assert_eq!(plaintext, decipher(&key, &ciphertext));
} | identifier_body | |
cipher.rs | //! Implements the basic XTEA cipher routines as described in the
//! paper (http://en.wikipedia.org/wiki/XTEA). These functions only
//! deal with a single 64-bit block of data at a time.
static NUM_ROUNDS: u32 = 32;
use super::{Key, Block};
/// Encrypts 64 bits of `input` using the `key`.
///
/// # Example:
/// `... |
#[test]
fn it_works() {
let key: Key = [10, 20, 30, 42];
let plaintext: Block = [300, 400];
let ciphertext = encipher(&key, &plaintext);
assert!(plaintext != ciphertext);
assert_eq!(plaintext, decipher(&key, &ciphertext));
} | }
[v0, v1]
} | random_line_split |
cipher.rs | //! Implements the basic XTEA cipher routines as described in the
//! paper (http://en.wikipedia.org/wiki/XTEA). These functions only
//! deal with a single 64-bit block of data at a time.
static NUM_ROUNDS: u32 = 32;
use super::{Key, Block};
/// Encrypts 64 bits of `input` using the `key`.
///
/// # Example:
/// `... | (key: &Key, input: &Block) -> Block {
let [mut v0, mut v1] = *input;
let delta = 0x9E3779B9;
let mut sum: u32 = 0;
for _ in 0..NUM_ROUNDS {
v0 = v0.wrapping_add((((v1 << 4) ^ (v1 >> 5)).wrapping_add(v1)) ^ (sum.wrapping_add(key[(sum & 3) as usize])));
sum = sum.wrapping_add(delta);
... | encipher | identifier_name |
gulpfile.js | const gulp = require('gulp');
const sass = require('gulp-sass');
const rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer');
// Cactu scss source
const cactuUrl = './scss/**/*.scss';
const docUrl = './_sass/**/*.scss';
const sassOpts = {
outputStyle: 'compressed',
precison: 3,
errL... | ;
function docStyles() {
return gulp.src(docUrl)
.pipe(sass(sassOpts).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest('./assets/css'))
}
function compressedStyles() {
retu... | {
return gulp.src(cactuUrl)
.pipe(sass({
outputStyle: 'expanded'
}).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('./css'))
} | identifier_body |
gulpfile.js | const gulp = require('gulp');
const sass = require('gulp-sass');
const rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer');
// Cactu scss source
const cactuUrl = './scss/**/*.scss';
const docUrl = './_sass/**/*.scss';
const sassOpts = {
outputStyle: 'compressed',
precison: 3,
errL... | suffix: ".min"
}))
.pipe(gulp.dest('./css'))
}
gulp.task('sass', styles);
gulp.task('sass-doc', docStyles);
gulp.task('sass-compressed', compressedStyles);
gulp.task('cactu-build', gulp.parallel(styles, compressedStyles));
gulp.task('watch', () => {
gulp.watch([cactuUrl, docUrl], gulp.series(styles... | .pipe(rename({ | random_line_split |
gulpfile.js | const gulp = require('gulp');
const sass = require('gulp-sass');
const rename = require('gulp-rename');
const autoprefixer = require('gulp-autoprefixer');
// Cactu scss source
const cactuUrl = './scss/**/*.scss';
const docUrl = './_sass/**/*.scss';
const sassOpts = {
outputStyle: 'compressed',
precison: 3,
errL... | () {
return gulp.src(cactuUrl)
.pipe(sass(sassOpts).on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(rename({
suffix: ".min"
}))
.pipe(gulp.dest('./css'))
}
gulp.task('sass', styles);
gulp.task('sass-doc', docStyles);
... | compressedStyles | identifier_name |
config.js | /**
* config is the configuration wrapper object of the app
*/
var config = {
site : 'http://www.some.com',
domains : {
some : 'some.com'
},
el : {
productList : $('#product_list'),
productTemplate : $('#productTemplate'),
loader : $('#loader'),
err : $("#err")
},
imgPaths : {
logo : '../../img/logo... | fireabase : 'https://product-api.firebaseio.com'
},
errors : {
400 : '400',
500 : '500',
timeout : 'timeout'
},
errorMessages : {
serverConnectionFailed : 'Sunucuya bağlanılamıyor...',/*400*/
internalServerError : 'Sunucu taraflı bir hata oluştu...',/*500*/
timeout : 'Sayfa zaman aşımına uğradı. Lütfe... | favouriteProducts : 'http://127.0.0.1/ajax/favorite_products', | random_line_split |
python_runner_1.5.js | /*
python_runner:
Python code runner.
*/
var currentPythonContext = null;
function PythonInterpreter(context, msgCallback) {
this.context = context;
this.messageCallback = msgCallback;
this._code = '';
this._editor_filename = "<stdin>";
this.context.runner = this;
this._maxIterations = 4000;
... | if(highlighted.length == 0) {
return origValue;
} else if(highlighted.find('.ace_start').length > 0) {
var target = highlighted.find('.ace_start')[0];
} else {
var target = highlighted[0];
}
var bbox = target.getBoundingClientRect();
var leftPos = bbox.left+10;
var topPos ... |
var highlighted = $('.aceHighlight'); | random_line_split |
python_runner_1.5.js | /*
python_runner:
Python code runner.
*/
var currentPythonContext = null;
function PythonInterpreter(context, msgCallback) {
this.context = context;
this.messageCallback = msgCallback;
this._code = '';
this._editor_filename = "<stdin>";
this.context.runner = this;
this._maxIterations = 4000;
... |
};
this.unSkulptValue = function (origValue) {
// Transform a value, possibly a Skulpt one, into a printable value
if(typeof origValue !== 'object' || origValue === null) {
var value = origValue;
} else if(origValue.constructor === Sk.builtin.dict) {
var keys = Object.keys(origValue);
... | {
editor.session.removeMarker(this._editorMarker);
this._editorMarker = null;
} | conditional_block |
python_runner_1.5.js | /*
python_runner:
Python code runner.
*/
var currentPythonContext = null;
function PythonInterpreter(context, msgCallback) {
this.context = context;
this.messageCallback = msgCallback;
this._code = '';
this._editor_filename = "<stdin>";
this.context.runner = this;
this._maxIterations = 4000;
... | (context, msgCallback) {
return new PythonInterpreter(context, msgCallback);
};
| initBlocklyRunner | identifier_name |
python_runner_1.5.js | /*
python_runner:
Python code runner.
*/
var currentPythonContext = null;
function PythonInterpreter(context, msgCallback) {
this.context = context;
this.messageCallback = msgCallback;
this._code = '';
this._editor_filename = "<stdin>";
this.context.runner = this;
this._maxIterations = 4000;
... |
var funcs = ['toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toSource', 'toString', 'valueOf'];
for(var i = 0; i < funcs.length ; i++) {
this.pythonNumber.prototype[funcs[i]] = makePrototype(funcs[i]);
}
}
this.skToJs = function(val) {
// Convert Skulpt item to JavaScript
/... | {
return function() { return Number.prototype[func].call(this.val); }
} | identifier_body |
test_section_topics.py | # Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from pkg_resources import resource_filename
import marv_node.testing
from marv_node.testing import make_dataset, run_nodes, temporary_directory
from marv_robotics.detail import connections_section as node
from marv_store import Store
class ... | BAGS = [
resource_filename('marv_node.testing._robotics_tests', 'data/test_0.bag'),
resource_filename('marv_node.testing._robotics_tests', 'data/test_1.bag'),
]
async def test_node(self):
with temporary_directory() as storedir:
store = Store(storedir, {})
dataset... | identifier_body | |
test_section_topics.py | # Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from pkg_resources import resource_filename
import marv_node.testing
from marv_node.testing import make_dataset, run_nodes, temporary_directory
from marv_robotics.detail import connections_section as node
from marv_store import Store
class ... | self.assertNodeOutput(streams[0], node)
# TODO: test also header | dataset = make_dataset(self.BAGS)
store.add_dataset(dataset)
streams = await run_nodes(dataset, [node], store) | random_line_split |
test_section_topics.py | # Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from pkg_resources import resource_filename
import marv_node.testing
from marv_node.testing import make_dataset, run_nodes, temporary_directory
from marv_robotics.detail import connections_section as node
from marv_store import Store
class ... | (self):
with temporary_directory() as storedir:
store = Store(storedir, {})
dataset = make_dataset(self.BAGS)
store.add_dataset(dataset)
streams = await run_nodes(dataset, [node], store)
self.assertNodeOutput(streams[0], node)
# TODO: test ... | test_node | identifier_name |
jquery.validation.settings.js | jQuery(document).ready(function($){
var nameDefault = 'Your name...';
var emailDefault = 'Your email...';
var messageDefault = 'Your message...';
// Setting up existing forms
setupforms();
function setupforms() {
// Applying default values
setupDefaultText('#name',nameDefault);
setupDefault... | () {
if(!$('#form-contact').valid()) { return false; }
else { return true; }
}
$("#form-contact").ajaxForm({
beforeSubmit: validateContact,
type: "POST",
url: "assets/php/contact-form-process.php",
data: $("#form-contact").serialize(),
success: function(msg){
$("#form-message").ajaxComple... | validateContact | identifier_name |
jquery.validation.settings.js | jQuery(document).ready(function($){
var nameDefault = 'Your name...';
var emailDefault = 'Your email...';
var messageDefault = 'Your message...';
// Setting up existing forms
setupforms();
function setupforms() {
// Applying default values
setupDefaultText('#name',nameDefault);
setupDefault... |
function evalDefault(fieldID) {
if($(fieldID).val() != $(fieldID).attr('data-default')) {
return false;
}
else { return true; }
}
function hasDefaults(formType) {
switch (formType)
{
case "contact" :
if(evalDefault('#name') && evalDefault('#email') && evalDefault('#message')) { re... | {
$(fieldID).val(fieldDefault);
$(fieldID).attr('data-default', fieldDefault);
} | identifier_body |
jquery.validation.settings.js | jQuery(document).ready(function($){
var nameDefault = 'Your name...';
var emailDefault = 'Your email...';
var messageDefault = 'Your message...';
// Setting up existing forms
setupforms();
function setupforms() {
// Applying default values
setupDefaultText('#name',nameDefault);
setupDefault... |
else
{
result = '<span class="form-message-error"><i class="icon-thumbs-down"></i> ' + msg +'</span>';
clear = false;
}
$(this).html(result);
if(clear == true) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
}
});
}); | {
result = '<span class="form-message-success"><i class="icon-thumbs-up"></i> Your message was sent. Thank you!</span>';
clear = true;
} | conditional_block |
jquery.validation.settings.js | jQuery(document).ready(function($){
var nameDefault = 'Your name...';
var emailDefault = 'Your email...';
var messageDefault = 'Your message...';
// Setting up existing forms
setupforms();
function setupforms() {
// Applying default values
setupDefaultText('#name',nameDefault);
setupDefault... | }
});
function validateContact() {
if(!$('#form-contact').valid()) { return false; }
else { return true; }
}
$("#form-contact").ajaxForm({
beforeSubmit: validateContact,
type: "POST",
url: "assets/php/contact-form-process.php",
data: $("#form-contact").serialize(),
success: function(m... | }
| random_line_split |
commonconfig.py |
Copyright 2008, Red Hat, Inc
see AUTHORS
This software may be freely redistributed under the terms of the GNU
general public license.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.... | """
Default configuration values for certmaster items when
not specified in config file. | random_line_split | |
commonconfig.py | """
Default configuration values for certmaster items when
not specified in config file.
Copyright 2008, Red Hat, Inc
see AUTHORS
This software may be freely redistributed under the terms of the GNU
general public license.
You should have received a copy of the GNU General Public License
along with this program; if ... |
class MinionConfig(BaseConfig):
log_level = Option('INFO')
certmaster = Option('certmaster')
certmaster_port = IntOption(51235)
cert_dir = Option('/etc/pki/certmaster')
| log_level = Option('INFO')
listen_addr = Option('')
listen_port = IntOption(51235)
cadir = Option('/etc/pki/certmaster/ca')
cert_dir = Option('/etc/pki/certmaster')
certroot = Option('/var/lib/certmaster/certmaster/certs')
csrroot = Option('/var/lib/certmaster/certmaster/csrs')
cert_extensi... | identifier_body |
commonconfig.py | """
Default configuration values for certmaster items when
not specified in config file.
Copyright 2008, Red Hat, Inc
see AUTHORS
This software may be freely redistributed under the terms of the GNU
general public license.
You should have received a copy of the GNU General Public License
along with this program; if ... | (BaseConfig):
log_level = Option('INFO')
listen_addr = Option('')
listen_port = IntOption(51235)
cadir = Option('/etc/pki/certmaster/ca')
cert_dir = Option('/etc/pki/certmaster')
certroot = Option('/var/lib/certmaster/certmaster/certs')
csrroot = Option('/var/lib/certmaster/certmaster/csrs'... | CMConfig | identifier_name |
articles.js | $(function() {
$(".article-sidebar .sticky").css('width', $(".article-sidebar .sticky").width()-2);
$(".article-sidebar .sticky").sticky({topSpacing:45});
$(".article-sidebar ul.categories a").on('click', function(e) {
if (!$(this).siblings('ul').length)
return;
e.preventDefault(... | var $elem = $('article.body');
var $target = $('.article-suggest');
$window.scroll(checkSuggestion);
checkSuggestion();
}
// CONTRIBUTORS
$('.contributors > li .header').on('click', function(e) {
$(this).siblings('ul').slideToggle();
});
}); | random_line_split | |
articles.js | $(function() {
$(".article-sidebar .sticky").css('width', $(".article-sidebar .sticky").width()-2);
$(".article-sidebar .sticky").sticky({topSpacing:45});
$(".article-sidebar ul.categories a").on('click', function(e) {
if (!$(this).siblings('ul').length)
return;
e.preventDefault(... | () {
var viewport_bottom = $window.scrollTop() + $window.height();
var height = $elem.height();
var bottom = $elem.offset().top + $elem.height();
if (bottom <= viewport_bottom) {
$target.fadeIn();
} else {
$target.fadeOut();
}
}
if ($('.art... | checkSuggestion | identifier_name |
articles.js | $(function() {
$(".article-sidebar .sticky").css('width', $(".article-sidebar .sticky").width()-2);
$(".article-sidebar .sticky").sticky({topSpacing:45});
$(".article-sidebar ul.categories a").on('click', function(e) {
if (!$(this).siblings('ul').length)
return;
e.preventDefault(... | else {
$target.fadeOut();
}
}
if ($('.article-suggest').length) {
var $window = $(window);
var $elem = $('article.body');
var $target = $('.article-suggest');
$window.scroll(checkSuggestion);
checkSuggestion();
}
// CONTRIBUTORS
$('.co... | {
$target.fadeIn();
} | conditional_block |
articles.js | $(function() {
$(".article-sidebar .sticky").css('width', $(".article-sidebar .sticky").width()-2);
$(".article-sidebar .sticky").sticky({topSpacing:45});
$(".article-sidebar ul.categories a").on('click', function(e) {
if (!$(this).siblings('ul').length)
return;
e.preventDefault(... |
if ($('.article-suggest').length) {
var $window = $(window);
var $elem = $('article.body');
var $target = $('.article-suggest');
$window.scroll(checkSuggestion);
checkSuggestion();
}
// CONTRIBUTORS
$('.contributors > li .header').on('click', function(e) {
... | {
var viewport_bottom = $window.scrollTop() + $window.height();
var height = $elem.height();
var bottom = $elem.offset().top + $elem.height();
if (bottom <= viewport_bottom) {
$target.fadeIn();
} else {
$target.fadeOut();
}
} | identifier_body |
solve0043.js | var library = require('./library.js');
var check_cond = function(num, div, start)
{
var n = '';
for(var i = start; i < start + 3; i++)
{
n = n + num.toString().charAt(i - 1);
}
if(parseInt(n) % div === 0)
{
return true;
}
return false; | var all = [2, 3, 5, 7, 11, 13, 17];
for(var i = 0; i < all.length; i += 1)
{
if(!check_cond(num, all[i], i + 2))
{
return false;
}
}
return true;
}
var solve = function ()
{
var sum = 0;
var start = 1234567890;
var end = 9876543210;
for(var... | }
var check_all = function(num)
{ | random_line_split |
solve0043.js | var library = require('./library.js');
var check_cond = function(num, div, start)
{
var n = '';
for(var i = start; i < start + 3; i++)
{
n = n + num.toString().charAt(i - 1);
}
if(parseInt(n) % div === 0)
{
return true;
}
return false;
}
var check_all = function(num)... |
if(n[6] % 5 != 0)
{
return false;
}
var b = n[5] * 10 + n[6] - 2 * n[7];
if(b % 7 != 0)
{
return false;
}
var c = n[6] * 10 + n[7] - n[8];
if(c % 11 != 0)
{
return false;
}
var d = n[7] * 10 + n[8] + 4 * n[9];
if(d % 13 != 0)
{
... | {
return false;
} | conditional_block |
model.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
"""
TR-55 Model Implementation
A mapping between variable/parameter names found in the TR-55 document
and variables used in this program are as follows:
* `precip` is referred to as P... | soil_type, land_use, bmp = split
runoff_per_cell = result['runoff-vol'] / n
liters = get_volume_of_runoff(runoff_per_cell, n, cell_res)
for pol in get_pollutants():
tree[pol] = get_pollutant_load(land_use, pol, liters)
def postpass(tree):
"""
Rem... | # perform water quality calculation
if n != 0: | random_line_split |
model.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
"""
TR-55 Model Implementation
A mapping between variable/parameter names found in the TR-55 document
and variables used in this program are as follows:
* `precip` is referred to as P... |
potential_retention = (1000.0 / curve_number) - 10
initial_abs = 0.2 * potential_retention
precip_minus_initial_abs = precip - initial_abs
numerator = pow(precip_minus_initial_abs, 2)
denominator = (precip_minus_initial_abs + potential_retention)
runoff = numerator / denominator
return min(... | return 0.0 | conditional_block |
model.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
"""
TR-55 Model Implementation
A mapping between variable/parameter names found in the TR-55 document
and variables used in this program are as follows:
* `precip` is referred to as P... |
precip = max(0.0, precip)
soil_type, land_use, bmp = cell.lower().split(':')
# If there is no precipitation, then there is no runoff or
# infiltration; however, there is evapotranspiration. (It is
# understood that over a period of time, this can lead to the sum
# of the three ... | """
This function ensures that runoff + et + inf <= precip.
NOTE: Infiltration is normally independent of the
precipitation level, but this function introduces a slight
dependency (that is, at very low levels of precipitation, this
function can cause infiltration to be smaller t... | identifier_body |
model.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
"""
TR-55 Model Implementation
A mapping between variable/parameter names found in the TR-55 document
and variables used in this program are as follows:
* `precip` is referred to as P... | (census, m2_per_pixel, precip):
"""
Compute the overall amount of water retained by infiltration/retention
type BMP's.
Result is a percent of runoff remaining after water is trapped in
infiltration/retention BMP's
"""
meters_per_inch = 0.0254
cubic_meters = census['runoff-vol'] * meters... | compute_bmp_effect | identifier_name |
main.py | # per-module import for actioninja
# standard imports
import sys # for tracebaks in on_error.
import json # to load the config file.
import traceback # also used to print tracebacks. I'm a lazy ass.
import asyncio # because we're using the async branch of discord.py.
from random import choice # for choosing game ids
... | ():
''' Executed when the bot successfully connects to Discord. '''
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
# pylint: disable=w1401
# pylint was freaking out about the ascii bullshit so I had to add that.
print("""
____ ____ ... | on_ready | identifier_name |
main.py | # per-module import for actioninja
# standard imports
import sys # for tracebaks in on_error.
import json # to load the config file.
import traceback # also used to print tracebacks. I'm a lazy ass.
import asyncio # because we're using the async branch of discord.py.
from random import choice # for choosing game ids
... |
client.run(config['token'])
# Here's the old manual-loop way of starting the bot.
# def main_task():
# '''
# I'm gonna be honest, I have *no clue* how asyncio works. This is all from
# the example in the docs.
# '''
# yield from client.login(config['email'], config['password'])
# yield from ... | '''
This event is basically a script-spanning `except` statement.
'''
# args[0] is the message that was recieved prior to the error. At least,
# it should be. We check it first in case the cause of the error wasn't a
# message.
print('An error has been caught.')
print(traceback.format_exc())... | identifier_body |
main.py | # per-module import for actioninja
# standard imports
import sys # for tracebaks in on_error.
import json # to load the config file.
import traceback # also used to print tracebacks. I'm a lazy ass.
import asyncio # because we're using the async branch of discord.py.
from random import choice # for choosing game ids
... |
for func in cacobot.base.posts:
await cacobot.base.posts[func](message, client)
@client.event
async def on_error(*args):
'''
This event is basically a script-spanning `except` statement.
'''
# args[0] is the message that was recieved prior to the error. At least,
# it should be. We ch... | command = message.content.split()[0][len(cacobot.base.config['invoker']):].lower()
# So basically if the message was ".Repeat Butt talker!!!" this
# would be "repeat"
if command in cacobot.base.functions:
if message.channel.is_private or\
message.channel.permissions_for(m... | conditional_block |
main.py | # per-module import for actioninja
# standard imports
import sys # for tracebaks in on_error.
import json # to load the config file.
import traceback # also used to print tracebacks. I'm a lazy ass.
import asyncio # because we're using the async branch of discord.py.
from random import choice # for choosing game ids
... | args[1].channel,
'{}\n{}: You caused {} **{}** with your command.'.format(
choice(config['error_messages']),
args[1].author.name,
aan(sys.exc_info()[0].__name__),
... | else:
await client.send_message( | random_line_split |
crawler.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
crawler.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
import csv
import urllib2
import urllib
import re
import os
import urlparse
import threading
import logging
import logging.handlers
import time
import random
import bs4
MINIMUM_PDF_SIZE = 4506
TASKS... |
except urllib2.URLError as e:
log.warn("%s\tURLError\t%s\tRetry:%i&Sleep:%.2f\t%s" %
(sbid, url, i, sleep_time, e.reason))
time.sleep(sleep_time)
raise ExceedMaximumRetryError(sbid=sbid, url=url)
if url.endswith('.pdf'):
#: sbid is no... | sleep_time = random.randint(0, 2 ** i - 1) | conditional_block |
crawler.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
crawler.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
import csv
import urllib2
import urllib
import re
import os
import urlparse
import threading
import logging
import logging.handlers
import time
import random
import bs4
MINIMUM_PDF_SIZE = 4506
TASKS... |
def get_completed_tasks(output_folder):
"""
Return downloaded tasks
"""
completed = set()
for f in os.listdir(output_folder):
filepath = os.path.join(output_folder, f)
with open(filepath, 'r') as ff:
head_line = ff.readline()
#if os.stat(filepath).st_size > MIN... | """
Returns:
[{'ScienceBaseID': a1b2c3d4, 'webLinks__uri': 'http://balabala'}, {}]
"""
l = []
with open(csv_filepath, 'r') as f:
reader = csv.DictReader(f, delimiter=',', quotechar='"')
for row in reader:
if 'Action' in row and row['Action'].lower() == 'ignore for now... | identifier_body |
crawler.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
crawler.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
import csv
import urllib2
import urllib
import re
import os
import urlparse
import threading
import logging
import logging.handlers
import time
import random
import bs4
MINIMUM_PDF_SIZE = 4506
TASKS... | _urlfetch(url, sbid, os.path.join(output_folder, "%s.%s.pdf" % (sbid, pdf_name)))
else:
page = _urlfetch(url, sbid)
soup = bs4.BeautifulSoup(page)
anchors = soup.findAll('a', attrs={'href': re.compile(".pdf$", re.I)})
if not anchors:
log.warn("%s\tNO_PDF_DETECTED\... | #: sbid is not unique, so use sbid+pdfname as new name
pdf_name = url.split('/')[-1].split('.')[0] | random_line_split |
crawler.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
crawler.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
import csv
import urllib2
import urllib
import re
import os
import urlparse
import threading
import logging
import logging.handlers
import time
import random
import bs4
MINIMUM_PDF_SIZE = 4506
TASKS... | (csv_filepath, output_folder='pdfs', exclude_downloaded=False):
"""main function
"""
global TASKS
TASKS = get_tasks(csv_filepath)
excluded = set()
if exclude_downloaded:
excluded = get_completed_tasks(output_folder)
for i in range(128):
t = threading.Thread(target=crawler, ... | crawl | identifier_name |
api_receive_application.py | import ssl
import logging
import tornado.ioloop
import tornado.web
import sys
from tornado import httpclient
from functools import partial
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
from create_receive_handler import ReceiveHandler
from wallet_notify_handler i... |
def log_start_data(self):
self.log('PARAM','BEGIN')
self.log('PARAM','port' ,self.options.port)
self.log('PARAM','log' ,self.options.log)
self.log('PARAM','db_echo' ,self.options.db_echo)
self.log('PARAM','db_engine' ,self.options.db_... | log_msg = command + ',' + key
if value:
try:
log_msg += ',' + value
except Exception,e :
try:
log_msg += ',' + str(value)
except Exception,e :
try:
log_msg += ',' + unicode(value)
except Exception,e :
log_msg += ', [object]'
... | identifier_body |
api_receive_application.py | import ssl
import logging
import tornado.ioloop
import tornado.web
import sys
from tornado import httpclient
from functools import partial
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
from create_receive_handler import ReceiveHandler
from wallet_notify_handler i... | if value:
try:
log_msg += ',' + value
except Exception,e :
try:
log_msg += ',' + str(value)
except Exception,e :
try:
log_msg += ',' + unicode(value)
except Exception,e :
log_msg += ', [object]'
self.replay_logger.info( ... | random_line_split | |
api_receive_application.py | import ssl
import logging
import tornado.ioloop
import tornado.web
import sys
from tornado import httpclient
from functools import partial
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
from create_receive_handler import ReceiveHandler
from wallet_notify_handler i... |
self.replay_logger.info( log_msg )
def log_start_data(self):
self.log('PARAM','BEGIN')
self.log('PARAM','port' ,self.options.port)
self.log('PARAM','log' ,self.options.log)
self.log('PARAM','db_echo' ,self.options.db_echo)
self.log('PARAM'... | try:
log_msg += ',' + value
except Exception,e :
try:
log_msg += ',' + str(value)
except Exception,e :
try:
log_msg += ',' + unicode(value)
except Exception,e :
log_msg += ', [object]' | conditional_block |
api_receive_application.py | import ssl
import logging
import tornado.ioloop
import tornado.web
import sys
from tornado import httpclient
from functools import partial
from sqlalchemy import create_engine, func
from sqlalchemy.orm import scoped_session, sessionmaker
from create_receive_handler import ReceiveHandler
from wallet_notify_handler i... | (self, forwarding_address):
url = forwarding_address.get_callback_url()
self.log('EXECUTE', 'curl ' + url)
context = ssl._create_unverified_context()
http_client = httpclient.AsyncHTTPClient(defaults=dict(ssl_options=context))
http_client.fetch(url, partial(self.on_handle_callback_url, forwarding_ad... | invoke_callback_url | identifier_name |
scrolltofixed-tests.ts | $(document).ready(function() {
$('#mydiv').scrollToFixed();
});
$(document).ready(function() {
$('.header').scrollToFixed({
preFixed: function() { $(this).find('h1').css('color', 'blue'); },
postFixed: function() { $(this).find('h1').css('color', ''); }
});
$('.footer').scrollToFixed( {
... | var limit = $('.footer').offset().top - $('#summary').outerHeight(true) - 10;
return limit;
},
zIndex: 999,
preFixed: function() { $(this).find('.title').css('color', 'blue'); },
preAbsolute: function() { $(this).find('.title').css('color', 'red'); },
post... |
$('#summary').scrollToFixed({
marginTop: $('.header').outerHeight() + 10,
limit: function() { | random_line_split |
config.py | from network import WLAN
###############################################################################
# Settings for WLAN STA mode
###############################################################################
WLAN_MODE = 'off'
#WLAN_SSID = ''
#WLAN_AUTH = (WLAN.WPA2,'')
#################... | # Settings for mode 'abp'
#LORA_ABP_DEVADDR = ''
#LORA_ABP_NETKEY = ''
#LORA_ABP_APPKEY = ''
# Interval between measures transmitted to TTN.
# Measured airtime of transmission is 56.6 ms, fair use policy limits us to
# 30 seconds per day (= roughly 500 messages). We default to a 180 second
# interval (=480 messag... | # Settings for mode 'otaa'
LORA_OTAA_EUI = '70B3D57EF0001ED4'
LORA_OTAA_KEY = None # See README.md for instructions!
| random_line_split |
setup.py | """
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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
... | version = "0.1.1"
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="tortoise",
version=version,
author="Claude SIMON",
# author_email="author@example.com",
description="Turtle graphics on the web.",
keywords="turtle, web",
long_descripti... |
import setuptools
| random_line_split |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... | &[]
};
Message::deserialize(&message[..3], text)
}
}
} | random_line_split | |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... | {
pub identity: String,
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub enum Message {
ADL { ops: Vec<String> },
AOP { character: String },
BRO { message: String },
CDS {
channel: String,
description: String,
},
CHA { channels: Vec<String> },
CIU {
sender:... | UserObject | identifier_name |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... |
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ParseError::*;
match *self {
Json(ref err) => err.fmt(f),
InvalidMessage => "Invalid F-Chat message received.".fmt(f),
}
}
}
impl ::std::error::Error for Parse... | {
ParseError::Json(error)
} | identifier_body |
server.rs | use enums::*;
use serde_json as json;
use std::fmt;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct PublicChannel {
pub name: String,
pub mode: ChannelMode,
pub characters: i32,
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ORSDetails {
pub name: String,
pub chara... |
}
}
| {
let text = if message.len() >= 4 {
&message[4..]
} else {
&[]
};
Message::deserialize(&message[..3], text)
} | conditional_block |
MetadataList.tsx | /*
MIT License
Copyright (c) 2020 Looker Data Sciences, Inc.
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, modi... | children: React.ReactNode
compact?: boolean
}) => {
if (compact) {
return (
<Flex mb="small">
<FlexItem flex="0 0 auto">
<Text fontSize="medium" fontWeight="semiBold">
{label}
</Text>
</FlexItem>
<FlexItem textAlign="right" flex="1 1 auto">
... | }: {
label: string
aux?: string | random_line_split |
latinEntities.js | //>>built
define("dojox/editor/plugins/nls/latinEntities", { root:
//begin v1.x content
({
/* These are already handled in the default RTE
amp:"ampersand",lt:"less-than sign",
gt:"greater-than sign",
nbsp:"no-break space\nnon-breaking space",
quot:"quote",
*/
iexcl:"inverted exclamation mark",
cent:"cent si... | Epsilon:"Greek capital letter epsilon",
Zeta:"Greek capital letter zeta",
Eta:"Greek capital letter eta",
Theta:"Greek capital letter theta",
Iota:"Greek capital letter iota",
Kappa:"Greek capital letter kappa",
Lambda:"Greek capital letter lambda",
Mu:"Greek capital letter mu",
Nu:"Greek capital letter nu",
... | random_line_split | |
freedesktop_notify_zh_CN.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_CN" version="2.1">
<context>
<name>@default</name>
<message>
<source>Notifications</source>
<translation type="unfinished"/> | <message>
<source>Number of quoted characters</source>
<translation type="unfinished"/>
</message>
<message>
<source>System notifications</source>
<translation type="unfinished"/>
</message>
<message>
<source>Use custom expiration timeout</source>
<tra... | </message>
<message numerus="yes">
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message> | random_line_split |
run_double.py | """
Copyright 2016 Rasmus Larsen
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE.txt file for details.
"""
import sys
import time
from sacred import Experiment
from core.ALEEmulator import ALEEmulator
from dqn.Agent import Agent
from dqn.DoubleDQN import DoubleDQN
e... |
@ex.automain
def main(_config, _log):
sys.stdout = open('log_' + _config['rom_name'] + time.strftime('%H%M%d%m', time.gmtime()), 'w', buffering=True)
print "#{}".format(_config)
emu = ALEEmulator(_config)
_config['num_actions'] = emu.num_actions
net = DoubleDQN(_config)
agent = Agent(emu, ne... | emu = ALEEmulator(_config)
_config['num_actions'] = emu.num_actions
net = DoubleDQN(_config)
net.load(_config['rom_name'])
agent = Agent(emu, net, _config)
agent.next(0) # put a frame into the replay memory, TODO: should not be necessary
agent.test() | identifier_body |
run_double.py | """
Copyright 2016 Rasmus Larsen
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE.txt file for details.
"""
import sys
import time
from sacred import Experiment
from core.ALEEmulator import ALEEmulator
from dqn.Agent import Agent
from dqn.DoubleDQN import DoubleDQN
e... | filter_sizes = [8, 4, 3]
strides = [4, 2, 1]
state_frames = 4
fc_layers = 1
fc_units = [512]
in_width = 84
in_height = 84
discount = 0.99
device = '/gpu:0'
lr = 0.00025
opt_decay = 0.95
momentum = 0.0
opt_eps = 0.01
target_sync = 1e4
clip_delta = 1.0
tenso... |
@ex.config
def net_config():
conv_layers = 3
conv_units = [32, 64, 64] | random_line_split |
run_double.py | """
Copyright 2016 Rasmus Larsen
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE.txt file for details.
"""
import sys
import time
from sacred import Experiment
from core.ALEEmulator import ALEEmulator
from dqn.Agent import Agent
from dqn.DoubleDQN import DoubleDQN
e... | (_config):
emu = ALEEmulator(_config)
_config['num_actions'] = emu.num_actions
net = DoubleDQN(_config)
net.load(_config['rom_name'])
agent = Agent(emu, net, _config)
agent.next(0) # put a frame into the replay memory, TODO: should not be necessary
agent.test()
@ex.automain
def main(_con... | test | identifier_name |
reports.py | from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ugettex... |
@property
def headers(self):
h = [
DataTablesColumn(_("Affected User"), sortable=False),
DataTablesColumn(_("Modified by User"), sortable=False),
DataTablesColumn(_("Action"), prop_name='action'),
DataTablesColumn(_("Via"), prop_name='changed_via'),
... | """
Get slugs and human-friendly names for the properties that are available
for filtering and/or displayed by default in the report, without
needing to click "See More".
"""
if domain_has_privilege(domain, privileges.APP_USER_PROFILES):
user_data_label = _("profile o... | identifier_body |
reports.py | from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ugettex... | record.user_repr,
record.changed_by_repr,
_get_action_display(record.action),
record.changed_via,
self._user_history_details_cell(record.changes, domain),
self._html_list(list(get_messages(record.change_messages))),
ServerTime(record.ch... | return [ | random_line_split |
reports.py | from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ugettex... | (self, user_ids, changed_by_user_ids, user_property, actions, user_upload_record_id):
filters = Q(for_domain__in=self._for_domains())
if user_ids:
filters = filters & Q(user_id__in=user_ids)
if changed_by_user_ids:
filters = filters & Q(changed_by__in=changed_by_user_id... | _build_query | identifier_name |
reports.py | from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ugettex... |
if self.datespan:
filters = filters & Q(changed_at__lt=self.datespan.enddate_adjusted,
changed_at__gte=self.datespan.startdate)
return UserHistory.objects.filter(filters)
def _for_domains(self):
return BillingAccount.get_account_by_domain(self... | filters = filters & Q(user_upload_record_id=user_upload_record_id) | conditional_block |
text_info.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates};
use crate::tree::Count;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TextInfo {
pub(crate) bytes: Count,
pub(crate) chars: Count,
pub(crate) utf16_surrogates: Count,
p... | impl TextInfo {
#[inline]
pub fn new() -> TextInfo {
TextInfo {
bytes: 0,
chars: 0,
utf16_surrogates: 0,
line_breaks: 0,
}
}
#[inline]
pub fn from_str(text: &str) -> TextInfo {
TextInfo {
bytes: text.len() as Count,... | random_line_split | |
text_info.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates};
use crate::tree::Count;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TextInfo {
pub(crate) bytes: Count,
pub(crate) chars: Count,
pub(crate) utf16_surrogates: Count,
p... |
}
impl Add for TextInfo {
type Output = Self;
#[inline]
fn add(self, rhs: TextInfo) -> TextInfo {
TextInfo {
bytes: self.bytes + rhs.bytes,
chars: self.chars + rhs.chars,
utf16_surrogates: self.utf16_surrogates + rhs.utf16_surrogates,
line_breaks: se... | {
TextInfo {
bytes: text.len() as Count,
chars: count_chars(text) as Count,
utf16_surrogates: count_utf16_surrogates(text) as Count,
line_breaks: count_line_breaks(text) as Count,
}
} | identifier_body |
text_info.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use crate::str_utils::{count_chars, count_line_breaks, count_utf16_surrogates};
use crate::tree::Count;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TextInfo {
pub(crate) bytes: Count,
pub(crate) chars: Count,
pub(crate) utf16_surrogates: Count,
p... | (&mut self, other: TextInfo) {
*self = *self + other;
}
}
impl Sub for TextInfo {
type Output = Self;
#[inline]
fn sub(self, rhs: TextInfo) -> TextInfo {
TextInfo {
bytes: self.bytes - rhs.bytes,
chars: self.chars - rhs.chars,
utf16_surrogates: self.u... | add_assign | identifier_name |
create-api.component.ts | import {
Component
} from '@angular/core';
import {
JsonDataService
} from '../../Services/jsonData.service';
var validator = require('../../../lib/lib-validator');
var selectKeysObj = require('../../../lib/lib-selectKey');
@Component({
selector: 'create-api',
templateUrl: './create-api.component.html',
st... | this.selectKey = "";
if (oldSelectElement.length !== 0) {
oldSelectElement[0].classList.remove(selectedClass);
}
if (!element.classList.contains(selectedClass)) {
this.selectKey = element.textContent;
element.classList.add(selectedClass);
}
}
onSelectPrettyJson(): void {
//th... | var element = event.target;
var oldSelectElement = document.getElementsByClassName(selectedClass); | random_line_split |
create-api.component.ts | import {
Component
} from '@angular/core';
import {
JsonDataService
} from '../../Services/jsonData.service';
var validator = require('../../../lib/lib-validator');
var selectKeysObj = require('../../../lib/lib-selectKey');
@Component({
selector: 'create-api',
templateUrl: './create-api.component.html',
st... | else {
alert('Please enter correctly data');
}
}
onShowSelectKey(): void {
let jsonString = this.jsonStringValue;
let keys = selectKeysObj.selectEnablesKeys(jsonString);
this.enablesKeys = keys;
}
onSelectKey(event: any): void {
var selectedClass = 'keysModal__keyButton--active';
... | {
var result = this.jsonDataService.createJsonData(jsonString, describe,this.selectKey);
} | conditional_block |
create-api.component.ts | import {
Component
} from '@angular/core';
import {
JsonDataService
} from '../../Services/jsonData.service';
var validator = require('../../../lib/lib-validator');
var selectKeysObj = require('../../../lib/lib-selectKey');
@Component({
selector: 'create-api',
templateUrl: './create-api.component.html',
st... |
get errorMsgValue() {
return this._errorMsg;
}
}
| {
try {
this._jsonString = JSON.parse(v);
this._errorMsg = "";
var element = document.getElementsByClassName('json__createButton')[0];
element["disabled"] = false;
element.classList.add('json__createButton--active');
} catch (e) {
this._errorMsg = "error this string not json";
};
... | identifier_body |
create-api.component.ts | import {
Component
} from '@angular/core';
import {
JsonDataService
} from '../../Services/jsonData.service';
var validator = require('../../../lib/lib-validator');
var selectKeysObj = require('../../../lib/lib-selectKey');
@Component({
selector: 'create-api',
templateUrl: './create-api.component.html',
st... | () {
return this._describe;
}
set describeValue(s: string) {
this._describe = s;
}
get jsonStringValue() {
return this._jsonString;
}
set jsonStringValue(v: string) {
try {
this._jsonString = JSON.parse(v);
this._errorMsg = "";
var element = document.getElementsByClassName(... | describeValue | identifier_name |
issue-15381.rs | // Copyright 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-MIT or ... | {
let values: Vec<u8> = vec![1,2,3,4,5,6,7,8];
for
[x,y,z]
//~^ ERROR refutable pattern in `for` loop binding: `[]` not covered
in values.as_slice().chunks(3).filter(|&xs| xs.len() == 3) {
println!("y={}", y);
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.