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 |
|---|---|---|---|---|
parser.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The context within which CSS code is parsed.
use context::QuirksMode;
use cssparser::{Parser, SourceLocation,... | (
stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
line_number_offset: u64,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_orig... | new_with_line_number_offset | identifier_name |
any_ambiguous_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... | (&self) -> AnyAmbiguousAliases {
match self {
Self::NONE => AnyAmbiguousAliases::NONE,
Self::M1(_) => AnyAmbiguousAliases::M1,
Self::M2(_) => AnyAmbiguousAliases::M2,
Self::M3(_) => AnyAmbiguousAliases::M3,
}
}
pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<fl... | any_ambiguous_aliases_type | identifier_name |
any_ambiguous_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... | pub enum AnyAmbiguousAliasesT {
NONE,
M1(Box<MonsterT>),
M2(Box<MonsterT>),
M3(Box<MonsterT>),
}
impl Default for AnyAmbiguousAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyAmbiguousAliasesT {
pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases {
match self {
Self::NONE... | pub struct AnyAmbiguousAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)] | random_line_split |
Laura_Two_Layers.py | from jobman import DD, expand, flatten
import pynet.layer as layer
from pynet.model import *
from pynet.layer import *
from pynet.datasets.mnist import Mnist, Mnist_Blocks
import pynet.datasets.spec as spec
import pynet.datasets.mnist as mnist
import pynet.datasets.transfactor as tf
import pynet.datasets.mapping as ma... | (AE):
def __init__(self, state):
self.state = state
def build_model(self, input_dim):
with open(os.environ['PYNET_SAVE_PATH'] + '/'
+ self.state.hidden1.model + '/model.pkl') as f1:
model1 = cPickle.load(f1)
with open(os.environ['PYNET_SAVE_PATH'] + '/... | Laura_Two_Layers | identifier_name |
Laura_Two_Layers.py | from jobman import DD, expand, flatten
import pynet.layer as layer
from pynet.model import *
from pynet.layer import *
from pynet.datasets.mnist import Mnist, Mnist_Blocks
import pynet.datasets.spec as spec
import pynet.datasets.mnist as mnist
import pynet.datasets.transfactor as tf
import pynet.datasets.mapping as ma... | def build_model(self, input_dim):
with open(os.environ['PYNET_SAVE_PATH'] + '/'
+ self.state.hidden1.model + '/model.pkl') as f1:
model1 = cPickle.load(f1)
with open(os.environ['PYNET_SAVE_PATH'] + '/'
+ self.state.hidden2.model + '/model.pkl') as... | def __init__(self, state):
self.state = state
| random_line_split |
Laura_Two_Layers.py | from jobman import DD, expand, flatten
import pynet.layer as layer
from pynet.model import *
from pynet.layer import *
from pynet.datasets.mnist import Mnist, Mnist_Blocks
import pynet.datasets.spec as spec
import pynet.datasets.mnist as mnist
import pynet.datasets.transfactor as tf
import pynet.datasets.mapping as ma... |
log.info("Fine Tuning")
for layer in model.layers:
layer.dropout_below = None
layer.noise = None
train_obj = TrainObject(log = log,
dataset = dataset,
learning_rule = learning_rule,
... | database = self.build_database(dataset, learning_rule, learn_method, model)
database['records']['h1_model'] = self.state.hidden1.model
database['records']['h2_model'] = self.state.hidden2.model
log = self.build_log(database) | conditional_block |
Laura_Two_Layers.py | from jobman import DD, expand, flatten
import pynet.layer as layer
from pynet.model import *
from pynet.layer import *
from pynet.datasets.mnist import Mnist, Mnist_Blocks
import pynet.datasets.spec as spec
import pynet.datasets.mnist as mnist
import pynet.datasets.transfactor as tf
import pynet.datasets.mapping as ma... |
def build_model(self, input_dim):
with open(os.environ['PYNET_SAVE_PATH'] + '/'
+ self.state.hidden1.model + '/model.pkl') as f1:
model1 = cPickle.load(f1)
with open(os.environ['PYNET_SAVE_PATH'] + '/'
+ self.state.hidden2.model + '/model.pkl')... | self.state = state | identifier_body |
clipComb.py | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create pipeline
#
pl3d = vtk.vtkMultiBlockPLOT3DReader()
pl3d.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin")
pl3d.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin")
pl3... | renWin.Render()
#iren.Start() | # render the image
#
| random_line_split |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("... | () {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let opts = initialize_args();
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts)... | main | identifier_name |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("... | };
if print_ast {
print!("{}", ast);
}
match typechecker::check(ast) {
Ok(_) => (),
Err(s) => {
println!("Typechecker error: {}", s);
return;
}
}
} | println!("{}", s);
return;
} | random_line_split |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("... |
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let opts = initialize_args();
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&progr... | {
let mut opts = Options::new();
opts.optopt("O", "", "set optimization level", "[0-3]");
opts.optflag("h", "help", "print this help menu");
opts.optflag("", "ast", "print the ast");
return opts;
} | identifier_body |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("... |
let print_ast = matches.opt_present("ast");
let filename = if !matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
let mut input = File::open(filename).unwrap();
let mut code = String::new();
input.read_to_string(&mut... | {
print_usage(&program, opts);
return;
} | conditional_block |
keyboard.js | var EA_keys = {8:"Retour arriere",9:"Tabulation",12:"Milieu (pave numerique)",13:"Entrer",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"Verr Maj",27:"Esc",32:"Espace",33:"Page up",34:"Page down",35:"End",36:"Begin",37:"Fleche gauche",38:"Fleche haut",39:"Fleche droite",40:"Fleche bas",44:"Impr ecran",45:"Inser",46:"Supp... | use=true;
break;
case "e":
editArea.execCommand("show_help");
use=true;
break;
case "z":
use=true;
editArea.execCommand("undo");
break;
case "y":
use=true;
editArea.execCommand("redo");
break;
default:
break;
}
}
// check to di... | {
switch(low_letter){
case "f":
editArea.execCommand("area_search");
use=true;
break;
case "r":
editArea.execCommand("area_replace");
use=true;
break;
case "q":
editArea.execCommand("close_all_inline_popup", e);
use=true;
break;
case "h":
editArea... | conditional_block |
keyboard.js | var EA_keys = {8:"Retour arriere",9:"Tabulation",12:"Milieu (pave numerique)",13:"Entrer",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"Verr Maj",27:"Esc",32:"Espace",33:"Page up",34:"Page down",35:"End",36:"Begin",37:"Fleche gauche",38:"Fleche haut",39:"Fleche droite",40:"Fleche bas",44:"Impr ecran",45:"Inser",46:"Supp... | (e) {
if (window.event) {
return (window.event.altKey);
} else {
if(e.modifiers)
return (e.altKey || (e.modifiers % 2));
else
return e.altKey;
}
};
// return true if Ctrl key is pressed
function CtrlPressed(e) {
if (window.event) {
return (window.event.ctrlKey);
} else {
return (e.... | AltPressed | identifier_name |
keyboard.js | var EA_keys = {8:"Retour arriere",9:"Tabulation",12:"Milieu (pave numerique)",13:"Entrer",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"Verr Maj",27:"Esc",32:"Espace",33:"Page up",34:"Page down",35:"End",36:"Begin",37:"Fleche gauche",38:"Fleche haut",39:"Fleche droite",40:"Fleche bas",44:"Impr ecran",45:"Inser",46:"Supp... |
var low_letter= letter.toLowerCase();
if(letter=="Page up" && !editArea.nav['isOpera']){
editArea.execCommand("scroll_page", {"dir": "up", "shift": ShiftPressed(e)});
use=true;
}else if(letter=="Page down" && !editArea.nav['isOpera']){
editArea.execCommand("scroll_page", {"dir": "down", "shift": S... | var use=false;
if (EA_keys[e.keyCode])
letter=EA_keys[e.keyCode];
else
letter=String.fromCharCode(e.keyCode);
| random_line_split |
keyboard.js | var EA_keys = {8:"Retour arriere",9:"Tabulation",12:"Milieu (pave numerique)",13:"Entrer",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"Verr Maj",27:"Esc",32:"Espace",33:"Page up",34:"Page down",35:"End",36:"Begin",37:"Fleche gauche",38:"Fleche haut",39:"Fleche droite",40:"Fleche bas",44:"Impr ecran",45:"Inser",46:"Supp... | ;
| {
if (window.event) {
return (window.event.shiftKey);
} else {
return (e.shiftKey || (e.modifiers>3));
}
} | identifier_body |
gen_sync.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June... | (RotatingMachine):
""" Synchronous generator model. A single standard synchronous model is defined for the CIM, with several variations indicated by the 'model type' attribute. This model can be used for all types of synchronous machines (salient pole, solid iron rotor, etc.).
"""
# <<< gen_sync.attribute... | GenSync | identifier_name |
gen_sync.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June... |
from google.appengine.ext import db
# >>> imports
class GenSync(RotatingMachine):
""" Synchronous generator model. A single standard synchronous model is defined for the CIM, with several variations indicated by the 'model type' attribute. This model can be used for all types of synchronous machines (salient po... | # <<< imports
# @generated
from dynamics.dynamics.rotating_machine import RotatingMachine
| random_line_split |
gen_sync.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June... |
# EOF -------------------------------------------------------------------------
| """ Synchronous generator model. A single standard synchronous model is defined for the CIM, with several variations indicated by the 'model type' attribute. This model can be used for all types of synchronous machines (salient pole, solid iron rotor, etc.).
"""
# <<< gen_sync.attributes
# @generated
... | identifier_body |
map.js | d.attr("d", path)
.attr("fill", function(d) { return color(d.properties.quantile); })
.attr("fill-opacity", 1)
.attr("stroke", "white")
.attr("stroke-width", "1px")
.call(tooltip)
.call(modal);
}
// g.school circle attributes
function circleAttr(d) {
d... | d3.select(sliders).selectAll("input").on("input", filter);
}
| conditional_block | |
map.js | var svg = d3.select(map).append("svg")
.attr("width", width + margin.width())
.attr("height", height + margin.height())
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var schools = svg.selectAll("g.school")
.data(zones.elementary.feat... | (d) {
var grades = [
{ name: "Elementary", value: 7095 },
{ name: "Middle", value: 7198 },
{ name: "High", value: 6557 }
];
var data = [
{ name: d.school, value: d.funding },
{ name: "Hamilton County average", value: 7234 }
];
g... | modalChart | identifier_name |
map.js | 1] }
}
// Tooltip
// ---------------------------------------------------------------------------
function tooltip(d) {
d.on("mousemove", function(d) {
var tooltip = d3.select("#tooltip").classed("hidden", false);
tooltip.attr("pointer-events", "none")
.style("left", d3.... | // Range input settings
var
grade = +(d3.select("#sliders #grade input")[0][0].value),
funding = +(d3.select("#sliders #funding input")[0][0].value),
minority = +(d3.select("#sliders #minority input")[0][0].value),
poverty = +(d3.select("#sliders #poverty input")[0][0].va... | identifier_body | |
map.js | ; })
.attr("r", 2)
.attr("fill", "#252525");
}
// Returns x, y positions from object's long/lat
function point(d) {
var point = projection([d.properties.longitude, d.properties.latitude]);
return { x: point[0], y: point[1] }
}
// Tooltip
// ------------------------... | district = +(d3.select("#sliders #district input")[0][0].value) | random_line_split | |
header.py | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... |
return "%.1f %s%s" % (num, 'Yi', suffix)
def print_header():
driver_info = version_formatter("""{version} {release}""")
git_info = version_formatter("""{{{branch}}} {githash} {clean}""")
datadir = core.get_environment("PSIDATADIR")
memory = sizeof_fmt(core.get_memory())
threads = str(core.get_... | if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0 | conditional_block |
header.py | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | submitted.
-----------------------------------------------------------------------
Psi4 started on: %s
Process ID: %6d
PSIDATADIR: %s
Memory: %s
Threads: %s
""" % (driver_info, git_info, time_string, pid, datadir, memory, threads)
core.print_out(header)
| driver_info = version_formatter("""{version} {release}""")
git_info = version_formatter("""{{{branch}}} {githash} {clean}""")
datadir = core.get_environment("PSIDATADIR")
memory = sizeof_fmt(core.get_memory())
threads = str(core.get_num_threads())
header = """
----------------------------------... | identifier_body |
header.py | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | -----------------------------------------------------------------------
Psi4: An Open-Source Ab Initio Electronic Structure Package
Psi4 %s
Git: Rev %s
R. M. Parrish, L. A. Burns, D. G. A. Smith, A. C. Simmonett,
A. E. DePrince III, E. G. ... | memory = sizeof_fmt(core.get_memory())
threads = str(core.get_num_threads())
header = """ | random_line_split |
header.py | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | (num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
def print_header():
driver_info = version_formatter("""{version} {release}""")
git_i... | sizeof_fmt | identifier_name |
nlt.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
def _process_example_precache(self, id_): # pylint: disable=arguments-differ
"""Loads data from paths.
"""
id_, base, cvis, lvis, warp, rgb, rgb_camspc, nn_id, nn_base, nn_rgb, \
nn_rgb_camspc = tf.py_function(
self._load_data, [id_], (
tf.st... | id_regex = re.compile(
r'trainvali_\d\d\d\d\d\d\d\d\d_{cam}_{light}'.format(**nn))
matched = [
x for x in self.data_paths.keys() if id_regex.search(x) is not None]
n_matches = len(matched)
if not matched:
return None
if n_matches == 1:
retu... | identifier_body |
nlt.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
super().__init__(config, mode, **kwargs)
# Trigger init. in a main thread before starting multi-threaded work.
# See http://yaqs/eng/q/6292200559345664 for details
Image.init()
def _glob(self):
# Handle holdouts
holdout_cam = self.config.get('DEFAULT', 'holdout_cam'... | for k, v in paths.items():
if k != 'complete':
paths[k] = join(self.data_root, v) | conditional_block |
nlt.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (self, config, mode, **kwargs):
self.data_root = config.get('DEFAULT', 'data_root')
data_status_path = self.data_root.rstrip('/') + '.json'
if not exists(data_status_path):
raise FileNotFoundError((
"Data status JSON not found at \n\t%s\nRun "
"$REPO/d... | __init__ | identifier_name |
nlt.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | cam_light = '_'.join(id_.split('_')[-2:])
if (self.mode == 'vali' and cam_light in holdout) or \
(self.mode != 'vali' and cam_light not in holdout):
ids_split.append(id_)
logger.info(
"Number of '%s' camera-light combinations: %d", self.mod... | return ids
# Training-validation split
ids_split = []
for id_ in ids:
# ID is {bin_mode}_{i:09d}_{cam}_{light} | random_line_split |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn main() | Some(p) => cwd = p,
None => println!("Error: Can not get home directory!")
}
continue;
}
let path: Option<Path> = if args[0].starts_with("~") { // ~/projects
match env::home_dir() {
Some(e) => {
let dir = e.join(args[0].slic... | {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your left shoes.");
let mut cwd = env::current_dir().unwrap();
loop {
print!("{}", ash::format::format(&cwd));
let rawinput = old_io::stdin().read_line().ok().expect("Error Occured");
let input = rawinput.as_slice().tr... | identifier_body |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn main() {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your le... |
},
Err(e) => println!("No such file or directory: \"{}\"", args[0])
}
}
None => println!("Failed to locate path")
}
}
"exit" => {
println!("Goodbye!");
break;
}
_ => {
let process = Command::new(cmd).cwd... | {
cwd = new
} | conditional_block |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn | () {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your left shoes.");
let mut cwd = env::current_dir().unwrap();
loop {
print!("{}", ash::format::format(&cwd));
let rawinput = old_io::stdin().read_line().ok().expect("Error Occured");
let input = rawinput.as_slice()... | main | identifier_name |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn main() {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your le... | continue;
}
let path: Option<Path> = if args[0].starts_with("~") { // ~/projects
match env::home_dir() {
Some(e) => {
let dir = e.join(args[0].slice_from(2)); //[~/]
Some(dir)
}, //hacky but whatever
None => Path::new_op... | //go home
match env::home_dir() {
Some(p) => cwd = p,
None => println!("Error: Can not get home directory!")
} | random_line_split |
views.py | from django.shortcuts import render,HttpResponse
from .models import Employee
from .models import Record
import datetime
import calendar
def wage_list(request):
return render(request,'app/wage_list.html',{})
def get_data(request):
date_from_user = str(request.POST.get('datepicker'))
date_from_user = date_from_us... |
emp_data.append({
'name_of_employee':temp[-1],
'salary':salary[-1],
'salary_payable' : salary_payable[-1],
'no_of_holiday' : no_of_holiday[-1],
'esi_cutting' : esi_cutting[-1],
'net_payable' : net_payable[-1],
'salary_deducted' : salary_deducted[-1],
'total_ot_hrs' : total_ot_hrs[-1],... | salary.append( int(filtered_record[i].Employee.pay_per_month) ) # Salary per month
salary_per_day.append(( round(int(filtered_record[i].Employee.pay_per_month)/total_working_days,2) ))
# name_of_employee.append(filtered_record[i].Employee.first_name)
temp.append(employees_list[i].Employee)
m=filtered_record[i... | conditional_block |
views.py | from django.shortcuts import render,HttpResponse
from .models import Employee
from .models import Record
import datetime
import calendar
def wage_list(request):
return render(request,'app/wage_list.html',{})
def | (request):
date_from_user = str(request.POST.get('datepicker'))
date_from_user = date_from_user.split(' ')# 1st month 2nd is year
print(date_from_user)
filtered_record = Record.objects.filter(date__year=date_from_user[1],date__month=date_from_user[0])
employees_list = list(filtered_record)
print(type(employee... | get_data | identifier_name |
views.py | from django.shortcuts import render,HttpResponse
from .models import Employee
from .models import Record
import datetime
import calendar
def wage_list(request):
return render(request,'app/wage_list.html',{})
def get_data(request):
| total_days_in_month = int(tupl[1])
total_working_days = int(total_days_in_month - ( no_of_sundays + no_of_saturdays))
# End to find no of working days
# To find net payable slary
no_of_employees = filtered_record.count()
salary_payable=[]
salary=[]
net_payable = []
no_of_holiday = []
salary_deducted = []
ne... | date_from_user = str(request.POST.get('datepicker'))
date_from_user = date_from_user.split(' ')# 1st month 2nd is year
print(date_from_user)
filtered_record = Record.objects.filter(date__year=date_from_user[1],date__month=date_from_user[0])
employees_list = list(filtered_record)
print(type(employees_list))
temp... | identifier_body |
views.py | from django.shortcuts import render,HttpResponse
from .models import Employee
from .models import Record
import datetime
import calendar
def wage_list(request):
return render(request,'app/wage_list.html',{})
def get_data(request):
date_from_user = str(request.POST.get('datepicker'))
date_from_user = date_from_us... | Ot_Salary = []
salary_per_day=[]
days_attended = []
esi_cutting = []
esi = 1.75
i=0
int_array=[]
name_of_employee=[]
for counter in range(no_of_employees):
int_array.append(int(counter))
emp_data = []
while i<no_of_employees:
salary.append( int(filtered_record[i].Employee.pay_per_month) ) # Salary pe... | no_of_holiday = []
salary_deducted = []
net_final_payable = []
total_ot_hrs = [] | random_line_split |
parser_ips.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from intelmq.lib import utils
from intelmq.lib.bot import Bot
from intelmq.lib.message import Event
class | (Bot):
def process(self):
report = self.receive_message()
if not report:
self.acknowledge_message()
return
if not report.contains("raw"):
self.acknowledge_message()
raw_report = utils.base64_decode(report.value("raw"))
raw_report = raw_... | MalwareGroupIPsParserBot | identifier_name |
parser_ips.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from intelmq.lib import utils
from intelmq.lib.bot import Bot
from intelmq.lib.message import Event
class MalwareGroupIPsParserBot(Bot):
def process(self):
report = self.receive_message()
if not report:
self.... | bot = MalwareGroupIPsParserBot(sys.argv[1])
bot.start() | conditional_block | |
parser_ips.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from intelmq.lib import utils
from intelmq.lib.bot import Bot
from intelmq.lib.message import Event
class MalwareGroupIPsParserBot(Bot):
def process(self):
| row_splitted = row.split("<td>")
ip = row_splitted[1].split('">')[1].split("<")[0].strip()
time_source = row_splitted[6].replace("</td></tr>", "").strip()
time_source = time_source + " 00:00:00 UTC"
event = Event(report)
event.add('time.source', ... | report = self.receive_message()
if not report:
self.acknowledge_message()
return
if not report.contains("raw"):
self.acknowledge_message()
raw_report = utils.base64_decode(report.value("raw"))
raw_report = raw_report.split("<tbody>")[1]
raw_... | identifier_body |
parser_ips.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from intelmq.lib import utils
from intelmq.lib.bot import Bot
from intelmq.lib.message import Event
| class MalwareGroupIPsParserBot(Bot):
def process(self):
report = self.receive_message()
if not report:
self.acknowledge_message()
return
if not report.contains("raw"):
self.acknowledge_message()
raw_report = utils.base64_decode(report.value("raw... | random_line_split | |
reverse_graph.rs | use crate::core::{
property::{AddEdge, RemoveEdge},
Directed, Ensure, Graph, GraphDerefMut, GraphMut,
};
use delegate::delegate;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct ReverseGraph<C: Ensure>(C)
where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> ReverseGraph<C>
where
C::Graph: Graph<Dir... |
}
impl<C: Ensure + GraphDerefMut> AddEdge for ReverseGraph<C>
where
C::Graph: AddEdge<Directedness = Directed>,
{
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>
{
self.0.graph_mut().add_edge_weighted(sink... | {
Box::new(self.0.graph_mut().edges_between_mut(sink, source))
} | identifier_body |
reverse_graph.rs | use crate::core::{
property::{AddEdge, RemoveEdge},
Directed, Ensure, Graph, GraphDerefMut, GraphMut,
};
use delegate::delegate;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct ReverseGraph<C: Ensure>(C)
where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> ReverseGraph<C>
where
C::Graph: Graph<Dir... | C::Graph: GraphMut<Directedness = Directed>,
{
delegate! {
to self.0.graph_mut() {
fn all_vertices_weighted_mut<'a>(&'a mut self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a mut Self::VertexWeight)>>;
}
}
fn edges_between_mut<'a: 'b, 'b>(
&'a mut self,
source: impl 'b + Borrow<Self::Vertex>,
... | }
}
impl<C: Ensure + GraphDerefMut> GraphMut for ReverseGraph<C>
where | random_line_split |
reverse_graph.rs | use crate::core::{
property::{AddEdge, RemoveEdge},
Directed, Ensure, Graph, GraphDerefMut, GraphMut,
};
use delegate::delegate;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct ReverseGraph<C: Ensure>(C)
where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> ReverseGraph<C>
where
C::Graph: Graph<Dir... | (
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>
{
self.0.graph_mut().add_edge_weighted(sink, source, weight)
}
}
impl<C: Ensure + GraphDerefMut> RemoveEdge for ReverseGraph<C>
where
C::Graph: RemoveEdge<Directedness = Directed... | add_edge_weighted | identifier_name |
default_value_accessor.d.ts | /**
* @license
* Copyright Google Inc. 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
*/
import { ElementRef, InjectionToken, Renderer2 } from '@angular/core';
import { ControlValueAccessor } from './contro... | implements ControlValueAccessor {
private _renderer;
private _elementRef;
private _compositionMode;
/**
* @description
* The registered callback function called when an input event occurs on the input element.
*/
onChange: (_: any) => void;
/**
* @description
* The regi... | DefaultValueAccessor | identifier_name |
default_value_accessor.d.ts | /**
* @license
* Copyright Google Inc. 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
*/
import { ElementRef, InjectionToken, Renderer2 } from '@angular/core';
import { ControlValueAccessor } from './contro... | /**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
onTouched: () => void;
/** Whether the user is creating a composition string (IME events). */
private _composing;
constructor(_renderer: Renderer2, _elementRef: ElementRef, _... | * @description
* The registered callback function called when an input event occurs on the input element.
*/
onChange: (_: any) => void; | random_line_split |
parking.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import urllib2
import json
from plugins.plugin import Plugin
from time import time
from bytebot_config import BYTEBOT_HTTP_TIMEOUT, BYTEBOT_HTTP_MAXSIZE
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
class parking(Plugin):
def __init__(self):
|
def registerCommand(self, irc):
irc.registerCommand('!parking', 'Parken')
def _get_parking_status(self):
url = BYTEBOT_PLUGIN_CONFIG['parking']['url']
data = urllib2.urlopen(url, timeout=BYTEBOT_HTTP_TIMEOUT).read(
BYTEBOT_HTTP_MAXSIZE)
data = unicode(data, error... | pass | identifier_body |
parking.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import urllib2
import json | from plugins.plugin import Plugin
from time import time
from bytebot_config import BYTEBOT_HTTP_TIMEOUT, BYTEBOT_HTTP_MAXSIZE
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
class parking(Plugin):
def __init__(self):
pass
def registerCommand(self, irc):
irc.registerCommand('!parking', 'Park... | random_line_split | |
parking.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import urllib2
import json
from plugins.plugin import Plugin
from time import time
from bytebot_config import BYTEBOT_HTTP_TIMEOUT, BYTEBOT_HTTP_MAXSIZE
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
class parking(Plugin):
def __init__(self):
pass
d... | (self):
url = BYTEBOT_PLUGIN_CONFIG['parking']['url']
data = urllib2.urlopen(url, timeout=BYTEBOT_HTTP_TIMEOUT).read(
BYTEBOT_HTTP_MAXSIZE)
data = unicode(data, errors='ignore')
ret = json.loads(data)
return ret
def onPrivmsg(self, irc, msg, channel, user):
... | _get_parking_status | identifier_name |
parking.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import urllib2
import json
from plugins.plugin import Plugin
from time import time
from bytebot_config import BYTEBOT_HTTP_TIMEOUT, BYTEBOT_HTTP_MAXSIZE
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
class parking(Plugin):
def __init__(self):
pass
d... |
irc.last_parking = time()
except Exception as e:
print(e)
irc.msg(channel, 'Error while fetching data.')
else:
irc.msg(channel, "Don't overdo it ;)")
| name = data[x][u'name'].encode('ascii', 'ignore')
occupied = int(data[x][u'belegt'].encode('ascii',
'ignore'))
spaces = int(data[x][u'maximal'].encode('ascii', 'ignore'))
if(occupied < 0):
... | conditional_block |
runtornado.py |
import logging
import sys
from typing import Any, Callable
from django.conf import settings
from django.core.management.base import BaseCommand, \
CommandError, CommandParser
from tornado import ioloop
from tornado.log import app_log
# We must call zerver.tornado.ioloop_logging.instrument_tornado_ioloop
# before... |
def inner_run() -> None:
from django.conf import settings
from django.utils import translation
translation.activate(settings.LANGUAGE_CODE)
print("Validating Django models.py...")
self.check(display_num_errors=True)
print("\nDjango versi... | logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s') | conditional_block |
runtornado.py | import logging
import sys
from typing import Any, Callable
from django.conf import settings
from django.core.management.base import BaseCommand, \
CommandError, CommandParser
from tornado import ioloop
from tornado.log import app_log
# We must call zerver.tornado.ioloop_logging.instrument_tornado_ioloop
# before ... | help='[optional port number or ipaddr:port]\n '
'(use multiple ports to start multiple servers)')
parser.add_argument('--nokeepalive', action='store_true',
dest='no_keep_alive', default=False,
h... | parser.add_argument('addrport', nargs="?", type=str, | random_line_split |
runtornado.py |
import logging
import sys
from typing import Any, Callable
from django.conf import settings
from django.core.management.base import BaseCommand, \
CommandError, CommandParser
from tornado import ioloop
from tornado.log import app_log
# We must call zerver.tornado.ioloop_logging.instrument_tornado_ioloop
# before... | application = create_tornado_application(int(port))
if settings.AUTORELOAD:
zulip_autoreload_start()
# start tornado web server in single-threaded mode
http_server = httpserver.HTTPServer(application,
... | from django.conf import settings
from django.utils import translation
translation.activate(settings.LANGUAGE_CODE)
print("Validating Django models.py...")
self.check(display_num_errors=True)
print("\nDjango version %s" % (django.get_version(),))
p... | identifier_body |
runtornado.py |
import logging
import sys
from typing import Any, Callable
from django.conf import settings
from django.core.management.base import BaseCommand, \
CommandError, CommandParser
from tornado import ioloop
from tornado.log import app_log
# We must call zerver.tornado.ioloop_logging.instrument_tornado_ioloop
# before... | (BaseCommand):
help = "Starts a Tornado Web server wrapping Django."
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument('addrport', nargs="?", type=str,
help='[optional port number or ipaddr:port]\n '
'(use multiple p... | Command | identifier_name |
bundlestore.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Infinitepush Bundle Store
"""store for infinitepush bundles"""
import hashlib
import os
import subprocess
from tempfile import NamedTemporaryFile
fr... | raise error.Abort(
"Infinitepush failed to upload bundle to external store: %s"
% stderr
)
stdout_lines = stdout.splitlines()
if len(stdout_lines) == 1:
return stdout_lines[0]
else:
... | )
if returncode != 0: | random_line_split |
bundlestore.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Infinitepush Bundle Store
"""store for infinitepush bundles"""
import hashlib
import os
import subprocess
from tempfile import NamedTemporaryFile
fr... | (self, data):
filename = hashlib.sha1(data).hexdigest()
dirpath = self._dirpath(filename)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
with open(self._filepath(filename), "wb") as f:
f.write(data)
return filename
def read(self, key):
... | write | identifier_name |
bundlestore.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Infinitepush Bundle Store
"""store for infinitepush bundles"""
import hashlib
import os
import subprocess
from tempfile import NamedTemporaryFile
fr... |
else:
raise error.Abort(
"Infinitepush received bad output from %s: %s"
% (self.put_binary, stdout)
)
def read(self, handle):
# Won't work on windows because you can't open file second time without
# closing it
... | return stdout_lines[0] | conditional_block |
bundlestore.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Infinitepush Bundle Store
"""store for infinitepush bundles"""
import hashlib
import os
import subprocess
from tempfile import NamedTemporaryFile
fr... |
def write(self, data):
# Won't work on windows because you can't open file second time without
# closing it
with NamedTemporaryFile() as temp:
temp.write(data)
temp.flush()
temp.seek(0)
formatted_args = [arg.format(filename=temp.name) for arg... | p = subprocess.Popen(
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True
)
stdout, stderr = p.communicate()
returncode = p.returncode
return returncode, stdout, stderr | identifier_body |
physics.rs | use super::{Unit, ToUnit};
#[deriving(Eq, Ord)]
pub struct Vec2 {
pub x: Unit,
pub y: Unit,
}
impl Vec2 {
pub fn new<A: ToUnit, B: ToUnit>(x: A, y: B) -> Vec2 {
Vec2 {
x: x.to_unit(),
y: y.to_unit(),
}
}
pub fn norm(&self) -> Vec2 {
let len = self.l... | (&self) -> Vec2 {
*self
}
}
impl Add<Vec2, Vec2> for Vec2 {
fn add(&self, rhs: &Vec2) -> Vec2 {
Vec2 {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl<T: ToUnit> Mul<T, Vec2> for Vec2 {
fn mul(&self, rhs: &T) -> Vec2 {
let a = rhs.to_unit();
... | to_vec | identifier_name |
physics.rs | use super::{Unit, ToUnit};
#[deriving(Eq, Ord)]
pub struct Vec2 {
pub x: Unit,
pub y: Unit,
}
impl Vec2 {
pub fn new<A: ToUnit, B: ToUnit>(x: A, y: B) -> Vec2 {
Vec2 {
x: x.to_unit(),
y: y.to_unit(),
}
}
pub fn norm(&self) -> Vec2 {
let len = self.l... |
pub fn transform(&self, offset: Vec2) -> AABB {
AABB {
center: self.center + offset,
size: self.size,
}
}
pub fn is_collided_with(&self, other: &AABB) -> bool {
self.right() >= other.left() &&
self.left() <= other.right() &&
self.top() <= ot... | {
AABB {
center: Vec2::new(x, y),
size: Vec2::new(w, h),
}
} | identifier_body |
physics.rs | use super::{Unit, ToUnit};
#[deriving(Eq, Ord)]
pub struct Vec2 {
pub x: Unit,
pub y: Unit,
}
impl Vec2 {
pub fn new<A: ToUnit, B: ToUnit>(x: A, y: B) -> Vec2 {
Vec2 {
x: x.to_unit(),
y: y.to_unit(),
}
}
pub fn norm(&self) -> Vec2 {
let len = self.l... | }
}
}
/// x axis from left to right and y asix from top to bottom
pub struct AABB {
pub center: Vec2,
pub size: Vec2,
}
impl AABB {
pub fn new<A: ToUnit, B: ToUnit, C: ToUnit, D: ToUnit>(x: A, y: B, w: C, h: D) -> AABB {
AABB {
center: Vec2::new(x, y),
size: Ve... | random_line_split | |
test_SourceClip.py | from __future__ import print_function
import aaf
import aaf.mob
import aaf.define
import aaf.iterator
import aaf.dictionary
import aaf.storage
import aaf.component
import aaf.util
import traceback
import unittest
import os
from aaf.util import AUID, MobID
cur_dir = os.path.dirname(os.path.abspath(__file__))
sandbox... | unittest.main() | conditional_block | |
test_SourceClip.py | from __future__ import print_function
import aaf
import aaf.mob
import aaf.define
import aaf.iterator
import aaf.dictionary
import aaf.storage
import aaf.component
import aaf.util
import traceback
import unittest
import os
from aaf.util import AUID, MobID
cur_dir = os.path.dirname(os.path.abspath(__file__))
| class TestSourceClip(unittest.TestCase):
def test_basic(self):
test_file = os.path.join(sandbox, "test_SourceClip.aaf")
f = aaf.open(None, 't')
source_mob = f.create.SourceMob()
f.storage.add_mob(source_mob)
slot = source_mob.add_nil_ref(1, 100, "picture", "25/1")
... | sandbox = os.path.join(cur_dir,'sandbox')
if not os.path.exists(sandbox):
os.makedirs(sandbox)
| random_line_split |
test_SourceClip.py | from __future__ import print_function
import aaf
import aaf.mob
import aaf.define
import aaf.iterator
import aaf.dictionary
import aaf.storage
import aaf.component
import aaf.util
import traceback
import unittest
import os
from aaf.util import AUID, MobID
cur_dir = os.path.dirname(os.path.abspath(__file__))
sandbox... | (self):
test_file = os.path.join(sandbox, "test_SourceClip.aaf")
f = aaf.open(None, 't')
source_mob = f.create.SourceMob()
f.storage.add_mob(source_mob)
slot = source_mob.add_nil_ref(1, 100, "picture", "25/1")
source_ref = aaf.util.SourceRef()
source_ref.mob_i... | test_basic | identifier_name |
test_SourceClip.py | from __future__ import print_function
import aaf
import aaf.mob
import aaf.define
import aaf.iterator
import aaf.dictionary
import aaf.storage
import aaf.component
import aaf.util
import traceback
import unittest
import os
from aaf.util import AUID, MobID
cur_dir = os.path.dirname(os.path.abspath(__file__))
sandbox... |
s = str(source_clip.source_ref)
#slot = source_clip.resolve_slot()
assert source_clip.start_time == 10
source_clip.start_time = 5
assert source_clip.start_time == 5
# this wont reslove unless sourclip is actually added to file
#assert source_clip.resolve_ref()... | test_file = os.path.join(sandbox, "test_SourceClip.aaf")
f = aaf.open(None, 't')
source_mob = f.create.SourceMob()
f.storage.add_mob(source_mob)
slot = source_mob.add_nil_ref(1, 100, "picture", "25/1")
source_ref = aaf.util.SourceRef()
source_ref.mob_id = source_mob.mo... | identifier_body |
douala.js | "use strict";
var helpers = require("../../helpers/helpers");
exports["Africa/Douala"] = {
"guess:by:offset" : helpers.makeTestGuess("Africa/Douala", { offset: true, expect: "Africa/Lagos" }),
"guess:by:abbr" : helpers.makeTestGuess("Africa/Douala", { abbr: true, expect: "Africa/Lagos" }),
"1905" : helpers.make... | "1913" : helpers.makeTestYear("Africa/Douala", [
["1913-12-31T23:46:24+00:00", "23:59:59", "LMT", -815 / 60],
["1913-12-31T23:46:25+00:00", "00:16:25", "+0030", -30]
]),
"1919" : helpers.makeTestYear("Africa/Douala", [
["1919-08-31T23:29:59+00:00", "23:59:59", "+0030", -30],
["1919-08-31T23:30:00+00:00", "0... | ]),
| random_line_split |
CelestrackNORAD.py | '''
TURKSAT 4A
1 39522U 14007A 15301.78105273 .00000128 00000-0 00000+0 0 9996
2 39522 0.0299 272.9737 0004735 326.3457 120.6614 1.00271335 6265
'''
import math
import sys
import astropy.units as u
name = sys.stdin.readline().strip()
line1 = sys.stdin.readline()
line2 = sys.stdin.readline()
... |
launch = line1[11:14]
piece = line1[14]
epoch = line1[18:32]
i = float(line2[8:16])
raan = float(line2[17:25])
e = float("0." + line2[26:33].strip())
ap = float(line2[34:42])
ma = float(line2[43:51])
f = float(line2[52:63])
revs = int(line2[63:68])
t = 1.0 / f * u.day
print ap
print t
print t.to(u.second)
print 1.0... | year = year + 1000 | conditional_block |
CelestrackNORAD.py | '''
TURKSAT 4A
1 39522U 14007A 15301.78105273 .00000128 00000-0 00000+0 0 9996 |
import astropy.units as u
name = sys.stdin.readline().strip()
line1 = sys.stdin.readline()
line2 = sys.stdin.readline()
number = int(line1[2:7]) # + line1[7]
year = int(line1[9:11]) + 1000
if year < 1057: # 2k
year = year + 1000
launch = line1[11:14]
piece = line1[14]
epoch = line1[18:32]
i = float(line2[8:16])... | 2 39522 0.0299 272.9737 0004735 326.3457 120.6614 1.00271335 6265
'''
import math
import sys | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
extern crate app_units;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
ex... | mod generated_content;
pub mod incremental;
mod inline;
mod linked_list;
mod list_item;
mod model;
mod multicol;
pub mod opaque_node;
pub mod parallel;
mod persistent_list;
pub mod query;
pub mod sequential;
mod table;
mod table_caption;
mod table_cell;
mod table_colgroup;
mod table_row;
mod table_rowgroup;
mod table_w... | pub mod flow_ref;
mod fragment; | random_line_split |
PlaylistsDialog.js | /*
* Copyright (C) 2005-2010 Erik Nilsson, software on versionstudio point com
*
* 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... |
return selectedRecord;
}
}); | {
// make sure selected record matches exactly
// the combo box value
var record = this.comboBox.store.getAt(index);
if ( record.get("name")==this.comboBox.getValue() ) {
selectedRecord = record;
}
} | conditional_block |
PlaylistsDialog.js | /*
* Copyright (C) 2005-2010 Erik Nilsson, software on versionstudio point com
*
* 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... | * @param {String} name the name of the playlist
* @param {Number} playlistId the database id of the playlist or null if
* playlist does not exists in the database.
*/
"submit"
);
var store = new Ext.data.SimpleStore({
autoLoad: false,
data: this.data,
fields: ["na... | * Fired when the dialog is successfully submitted through
* a click on the OK button.
| random_line_split |
query.rs | races will cause undefined behavior",
),
DerefOfRawPointer => (
"dereference of raw pointer",
"raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
and cause data races: all of these are undefined behavior",
... |
}
impl<'a, K: Debug, V: Debug> Debug for MapPrinter<'a, K, V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_map().entries(self.0.take().unwrap()).finish()
}
}
/// Prints the generator variant name.
struct GenVar... | {
Self(Cell::new(Some(Box::new(iter))))
} | identifier_body |
query.rs | value in `TypeckResults`, this has
/// unerased regions.
pub concrete_opaque_types: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>,
pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
pub used_mut_upvars: SmallVec<[Field; 8]>,
}
/// The result of the `mir_const_qualif` query.
///
/// Each field ... | mir_for_ctfe_opt_const_arg | identifier_name | |
query.rs |
impl UnsafetyViolationDetails {
pub fn description_and_note(&self) -> (&'static str, &'static str) {
use UnsafetyViolationDetails::*;
match self {
CallToUnsafeFunction => (
"call to unsafe function",
"consult the function's documentation for information o... | AccessToUnionField,
MutationOfLayoutConstrainedField,
BorrowOfLayoutConstrainedField,
CallToFunctionWith,
} | random_line_split | |
naming-utils.ts | import { Languages } from "@autorest/codemodel";
import { Session } from "@autorest/extension-base";
import { removeSequentialDuplicates, fixLeadingNumber, deconstruct, Style, Styler } from "@azure-tools/codegen";
import { last } from "lodash";
export function getNameOptions(typeName: string, components: Array<string>... | export interface Nameable {
language: Languages;
}
export function setName(
thing: Nameable,
styler: Styler,
defaultValue: string,
overrides: Record<string, string>,
options?: SetNameOptions,
) {
setNameAllowEmpty(thing, styler, defaultValue, overrides, options);
if (!thing.language.default.name) {
... | const setNameDefaultOptions: SetNameOptions = Object.freeze({
removeDuplicates: true,
nameEmptyErrorMessage: `Name cannot be empty.`,
});
| random_line_split |
naming-utils.ts | import { Languages } from "@autorest/codemodel";
import { Session } from "@autorest/extension-base";
import { removeSequentialDuplicates, fixLeadingNumber, deconstruct, Style, Styler } from "@azure-tools/codegen";
import { last } from "lodash";
export function getNameOptions(typeName: string, components: Array<string>... |
/**
* Add a nameable entity to be styled and named.
* @param entity Nameable entity.
* @param styler Styler to use to render name.
* @param defaultName Default name in case entity doesn't have any specified.
*/
public add(entity: Nameable, styler: Styler, defaultName?: string) {
const initialNam... | }
| identifier_body |
naming-utils.ts | import { Languages } from "@autorest/codemodel";
import { Session } from "@autorest/extension-base";
import { removeSequentialDuplicates, fixLeadingNumber, deconstruct, Style, Styler } from "@azure-tools/codegen";
import { last } from "lodash";
export function getNameOptions(typeName: string, components: Array<string>... | {
private names = new Map<string, NamerEntry[]>();
public constructor(private session: Session<unknown>, private options: ScopeNamerOptions) {}
/**
* Add a nameable entity to be styled and named.
* @param entity Nameable entity.
* @param styler Styler to use to render name.
* @param defaultName Defa... | copeNamer | identifier_name |
naming-utils.ts | import { Languages } from "@autorest/codemodel";
import { Session } from "@autorest/extension-base";
import { removeSequentialDuplicates, fixLeadingNumber, deconstruct, Style, Styler } from "@azure-tools/codegen";
import { last } from "lodash";
export function getNameOptions(typeName: string, components: Array<string>... | }
}
return processedNames;
}
/**
* 2nd pass of the name resolving where it will deduplicate names used twice.
*/
private deduplicateNames(names: Map<string, Nameable[]>) {
const entityNames = new Set(names.keys());
for (const [_, entries] of names.entries()) {
if (entries.length... |
processedNames.set(selectedName, [entity]);
}
| conditional_block |
add_enchantment.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AddEnchantment {
target_uid: UID,
source_uid: UID,
}
impl AddEnchantment {
pub fn new(source_uid: UID, target_uid: UID) -> AddEnchantment {... | fn execute_rune(&self, mut game_state: &mut GameState) {
game_state.get_mut_minion(self.target_uid).unwrap().add_enchantment(self.source_uid);
}
fn can_see(&self, _controller: UID, _game_state: &GameState) -> bool {
return true;
}
fn to_json(&self) -> String {
json::encode(... | impl Rune for AddEnchantment { | random_line_split |
add_enchantment.rs | use rune_vm::Rune;
use rustc_serialize::json;
use game_state::GameState;
use minion_card::UID;
use hlua;
#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct AddEnchantment {
target_uid: UID,
source_uid: UID,
}
impl AddEnchantment {
pub fn | (source_uid: UID, target_uid: UID) -> AddEnchantment {
AddEnchantment {
source_uid: source_uid,
target_uid: target_uid,
}
}
}
implement_for_lua!(AddEnchantment, |mut _metatable| {});
impl Rune for AddEnchantment {
fn execute_rune(&self, mut game_state: &mut GameState) {... | new | identifier_name |
auth.js | var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var util = require('util');
var session = require('express-session');
var passport = require('passport');
module.exports = (app, url, appEnv, User) => {
app.use(session({
secret: process.env.SESSION_SECRET,
name: 'freelancalot',... | });
var googleOAuth = appEnv.getService('googleOAuth'),
googleOAuthCreds = googleOAuth.credentials;
passport.use(new GoogleStrategy({
clientID: googleOAuthCreds.clientID,
clientSecret: googleOAuthCreds.clientSecret,
callbackURL: util.format("http://%s%s", url, g... | done(null, user);
}) | random_line_split |
texture_swap.rs | extern crate rand;
extern crate piston_window;
extern crate image as im;
use piston_window::*;
fn main() {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let mut window: PistonWindow = WindowSettings::new("piston", [1024; 2]).build().unwrap();
let mut texture_context = TextureConte... | if counter > frames { break; }
}
window.draw_2d(&e, |c, g, _| {
clear([0.0, 0.0, 0.0, 1.0], g);
for p in &mut positions {
let (x, y) = *p;
*p = (x + (rand::random::<f64>() - 0.5) * 0.01,
y + (rand::random::<f64>() ... | let mut counter = 0;
window.set_bench_mode(true);
while let Some(e) = window.next() {
if e.render_args().is_some() {
counter += 1; | random_line_split |
texture_swap.rs | extern crate rand;
extern crate piston_window;
extern crate image as im;
use piston_window::*;
fn main() {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let mut window: PistonWindow = WindowSettings::new("piston", [1024; 2]).build().unwrap();
let mut texture_context = TextureConte... |
window.draw_2d(&e, |c, g, _| {
clear([0.0, 0.0, 0.0, 1.0], g);
for p in &mut positions {
let (x, y) = *p;
*p = (x + (rand::random::<f64>() - 0.5) * 0.01,
y + (rand::random::<f64>() - 0.5) * 0.01);
}
for i in 0... | {
counter += 1;
if counter > frames { break; }
} | conditional_block |
texture_swap.rs | extern crate rand;
extern crate piston_window;
extern crate image as im;
use piston_window::*;
fn | () {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let mut window: PistonWindow = WindowSettings::new("piston", [1024; 2]).build().unwrap();
let mut texture_context = TextureContext {
factory: window.factory.clone(),
encoder: window.factory.create_command_buffer().in... | main | identifier_name |
texture_swap.rs | extern crate rand;
extern crate piston_window;
extern crate image as im;
use piston_window::*;
fn main() | Texture::from_image(
&mut texture_context,
&img,
&TextureSettings::new()
).unwrap()
}).collect::<Vec<Texture<_>>>()
};
let mut positions = (0..texture_count)
.map(|_| (rand::random(), rand::random()))
.collect::<Vec... | {
let texture_count = 1024;
let frames = 200;
let size = 32.0;
let mut window: PistonWindow = WindowSettings::new("piston", [1024; 2]).build().unwrap();
let mut texture_context = TextureContext {
factory: window.factory.clone(),
encoder: window.factory.create_command_buffer().into(... | identifier_body |
table.service.js | 'use strict';
angular
.module('angular.extras.core')
.factory('AeTableService', ['NgTableParams', '$q', function () {
return {
/**
* Process a row column bases object-array structure and generate excel like cell number. The input should be
* like:
*
* var rows = [{
* ... |
column.columnNumber = columnNumber;
// Calculate the cell number like an excel sheet
column.cellNumber = String.fromCharCode(columnNumber + 64) + row.rowNumber;
});
});
}
};
}]); | {
row.mergedColumns--;
} | conditional_block |
table.service.js | 'use strict';
angular
.module('angular.extras.core')
.factory('AeTableService', ['NgTableParams', '$q', function () {
return {
/**
* Process a row column bases object-array structure and generate excel like cell number. The input should be
* like:
*
* var rows = [{
* ... | * columnNumber: 1,
* cellNumber: 'A2'
* }, {
* text: 'Ok',
* columnNumber: 3,
* cellNumber: 'C2'
* }]
* }]
*/
generateCellNumber: function (rows) {
angular.forEach(rows, function (row, rowIndex) {
... | * colspan: 2, | random_line_split |
mutex.rs | use alloc::boxed::Box;
use core::borrow::{Borrow, BorrowMut};
use core::ops::{Deref, DerefMut};
use core::cell::{Cell, RefCell, RefMut};
use crate::syscall;
use core::marker::Sync;
#[link(name="os_init", kind="static")]
extern "C" {
fn mutex_lock(lock: *mut i32) -> i32;
}
pub enum TryLockResult {
... | pub struct LockedResource<'a, T: 'a + ?Sized> {
mutex: &'a Mutex<T>,
data_ref: RefMut<'a, T>
}
impl<T> Mutex<T> {
pub fn new(t: T) -> Mutex<T> {
Self {
data: Box::new(RefCell::new(t)),
lock: Cell::new(0),
}
}
}
impl<T: ?Sized> Mutex<T> {
pub f... | random_line_split | |
mutex.rs | use alloc::boxed::Box;
use core::borrow::{Borrow, BorrowMut};
use core::ops::{Deref, DerefMut};
use core::cell::{Cell, RefCell, RefMut};
use crate::syscall;
use core::marker::Sync;
#[link(name="os_init", kind="static")]
extern "C" {
fn mutex_lock(lock: *mut i32) -> i32;
}
pub enum TryLockResult {
... | (&mut self) {
self.mutex.lock.set(0);
}
} | drop | identifier_name |
mutex.rs | use alloc::boxed::Box;
use core::borrow::{Borrow, BorrowMut};
use core::ops::{Deref, DerefMut};
use core::cell::{Cell, RefCell, RefMut};
use crate::syscall;
use core::marker::Sync;
#[link(name="os_init", kind="static")]
extern "C" {
fn mutex_lock(lock: *mut i32) -> i32;
}
pub enum TryLockResult {
... |
}
Ok(LockedResource {
mutex: &self,
data_ref: (*self.data).borrow_mut(),
})
}
}
impl<'a, T: ?Sized> Deref for LockedResource<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.data_ref.borrow()
}
}
... | {
return Err(TryLockResult::AlreadyLocked)
} | conditional_block |
__init__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------------------------------
# Program Name: Lychee
# Program Description: MEI document manager for formalized document control
# | # Purpose: Initialize Lychee.
#
# Copyright (C) 2016, 2017 Christopher Antila
#
# 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 opti... | # Filename: lychee/__init__.py | random_line_split |
setup.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | (src_dirs, strip=""):
ret = []
for src_dir in src_dirs:
for path, dnames, fnames in os.walk(src_dir):
for fname in fnames:
ret.append(os.path.join(path, fname).replace(strip, ""))
return ret
os.chdir(os.path.dirname(os.path.abspath(__file__)))
setup(
name = "shell",
version = VERSION,
url... | expand_package_data | identifier_name |
setup.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information | # "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHO... | # regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the | random_line_split |
setup.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... |
os.chdir(os.path.dirname(os.path.abspath(__file__)))
setup(
name = "shell",
version = VERSION,
url = 'http://github.com/cloudera/hue',
description = 'Shell interface in Hue',
author = 'Hue',
packages = find_packages('src'),
package_dir = {'': 'src'},
install_requires = ['setuptools', 'desktop'],
ent... | ret = []
for src_dir in src_dirs:
for path, dnames, fnames in os.walk(src_dir):
for fname in fnames:
ret.append(os.path.join(path, fname).replace(strip, ""))
return ret | identifier_body |
setup.py | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... |
return ret
os.chdir(os.path.dirname(os.path.abspath(__file__)))
setup(
name = "shell",
version = VERSION,
url = 'http://github.com/cloudera/hue',
description = 'Shell interface in Hue',
author = 'Hue',
packages = find_packages('src'),
package_dir = {'': 'src'},
install_requires = ['setuptools', 'des... | for path, dnames, fnames in os.walk(src_dir):
for fname in fnames:
ret.append(os.path.join(path, fname).replace(strip, "")) | conditional_block |
mnist.py | params, learning_rate):
grads = lasagne.updates.get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
for param, grad in zip(params, grads):
updates[param] = param - learning_rate * grad
return updates
def mysvrg(loss_or_grads, params, learning_rate,avg_gradient):
#Not Work... | download(filename)
# Read the labels in Yann LeCun's binary format.
with gzip.open(filename, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=8)
# The labels are vectors of integers now, that's exactly what we want.
return data
# We can now downloa... | # (Actually to range [0, 255/256], for compatibility to the version
return data / np.float32(256)
def load_mnist_labels(filename):
if not os.path.exists(filename): | random_line_split |
mnist.py | params, learning_rate):
grads = lasagne.updates.get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
for param, grad in zip(params, grads):
updates[param] = param - learning_rate * grad
return updates
def mysvrg(loss_or_grads, params, learning_rate,avg_gradient):
#Not Work... |
prediction = lasagne.layers.get_output(network)
loss = lasagne.objectives.categorical_crossentropy(prediction, target_var)
loss = loss.mean()
acc = T.mean(T.eq(T.argmax(prediction, axis=1), target_var),
dtype=theano.config.floatX)
params = lasagne.layers.get_all_params(networ... | print("Unrecognized model type %r." % model)
return | conditional_block |
mnist.py | (loss_or_grads, params, learning_rate):
grads = lasagne.updates.get_or_compute_grads(loss_or_grads, params)
updates = OrderedDict()
for param, grad in zip(params, grads):
updates[param] = param - learning_rate * grad
return updates
def mysvrg(loss_or_grads, params, learning_rate,avg_gradient)... | mysgd | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.