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 |
|---|---|---|---|---|
password.component.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { NgForm } from "@angular/forms";
import { Router } from "@angular/router";
import { User } from "../_Model/user.model";
import { UserService } from "../Services/user.service";
import "rxjs/add/operator/takeUntil";
import { Subject } from "rxjs/Sub... |
this.user.Password = f.value.Password;
this.userService.update(this.user)
.takeUntil(this.ngUnsubscribe)
.subscribe((result) => {
localStorage.removeItem("CurrentUser");
this.router.navigate(["/login"]);
});
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubs... | {
this.passwordsEqual = false;
setTimeout(() => { this.passwordsEqual = true; }, 4000);
return;
} | conditional_block |
password.component.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { NgForm } from "@angular/forms";
import { Router } from "@angular/router";
import { User } from "../_Model/user.model";
import { UserService } from "../Services/user.service";
import "rxjs/add/operator/takeUntil";
import { Subject } from "rxjs/Sub... |
}
| {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
} | identifier_body |
password.component.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { NgForm } from "@angular/forms";
import { Router } from "@angular/router";
import { User } from "../_Model/user.model";
import { UserService } from "../Services/user.service";
import "rxjs/add/operator/takeUntil";
import { Subject } from "rxjs/Sub... | setTimeout(() => { this.passwordsEqual = true; }, 4000);
return;
}
this.user.Password = f.value.Password;
this.userService.update(this.user)
.takeUntil(this.ngUnsubscribe)
.subscribe((result) => {
localStorage.removeItem("CurrentUser");
this.router.navigate(["/login"]);
}... | onSubmit(f: NgForm) {
if (f.value.Password !== f.value.RepeatPassword) {
this.passwordsEqual = false; | random_line_split |
password.component.ts | import { Component, OnDestroy, OnInit } from "@angular/core";
import { NgForm } from "@angular/forms";
import { Router } from "@angular/router";
import { User } from "../_Model/user.model";
import { UserService } from "../Services/user.service";
import "rxjs/add/operator/takeUntil";
import { Subject } from "rxjs/Sub... | implements OnInit, OnDestroy {
private ngUnsubscribe: Subject<void> = new Subject<void>();
public passwordsEqual = true;
public user: User;
constructor(private userService: UserService, private router: Router) {
this.user = JSON.parse(localStorage.getItem("currentUser"));
}
ngOnInit() {
}
onSub... | PasswordComponent | identifier_name |
main.rs | extern crate regex;
extern crate rustc_demangle;
mod dol;
mod assembler;
use std::fs::File;
use std::io::{BufWriter, BufReader};
use std::io::prelude::*;
use assembler::Assembler;
use regex::Regex;
use rustc_demangle::demangle;
use dol::DolFile;
use assembler::Instruction;
use std::env::args;
const FRAMEWORK_MAP: &'... |
}
write!(file, "{}", FRAMEWORK_MAP).unwrap();
}
fn main() {
let mut asm = String::new();
let _ = File::open("../../src/patch.asm")
.expect("Couldn't find \"src/patch.asm\". If you don't need to patch the dol, just \
create an empty file.")
.read_to_string(&mut asm);
... | {
writeln!(file,
" 00000000 {:06x} {} 4 {} \t{}",
length,
address,
fn_name,
source_file)
.unwrap();
} | conditional_block |
main.rs | extern crate regex;
extern crate rustc_demangle;
mod dol;
mod assembler;
use std::fs::File;
use std::io::{BufWriter, BufReader};
use std::io::prelude::*;
use assembler::Assembler;
use regex::Regex;
use rustc_demangle::demangle;
use dol::DolFile;
use assembler::Instruction;
use std::env::args;
const FRAMEWORK_MAP: &'... | () {
let mut asm = String::new();
let _ = File::open("../../src/patch.asm")
.expect("Couldn't find \"src/patch.asm\". If you don't need to patch the dol, just \
create an empty file.")
.read_to_string(&mut asm);
let lines = &asm.lines().collect::<Vec<_>>();
let mut ass... | main | identifier_name |
main.rs | extern crate rustc_demangle;
mod dol;
mod assembler;
use std::fs::File;
use std::io::{BufWriter, BufReader};
use std::io::prelude::*;
use assembler::Assembler;
use regex::Regex;
use rustc_demangle::demangle;
use dol::DolFile;
use assembler::Instruction;
use std::env::args;
const FRAMEWORK_MAP: &'static str = include... | extern crate regex; | random_line_split | |
main.rs | extern crate regex;
extern crate rustc_demangle;
mod dol;
mod assembler;
use std::fs::File;
use std::io::{BufWriter, BufReader};
use std::io::prelude::*;
use assembler::Assembler;
use regex::Regex;
use rustc_demangle::demangle;
use dol::DolFile;
use assembler::Instruction;
use std::env::args;
const FRAMEWORK_MAP: &'... | .unwrap();
let line_ender = if section.data.len() % 8 > 0 {
8 - (section.data.len() % 8)
} else {
0
};
for (i, byte) in section.data
.iter()
.chain(std::iter::repeat(&0).take(line_ender))
.enumerate() {
i... | {
let mut file = File::create("../../cheat.txt")
.expect("Couldn't create \"cheat.txt\". You might need to provide higher \
privileges.");
writeln!(file, "A8000000 00000001").unwrap();
for instruction in instructions {
writeln!(file,
"{:08X} {:08X}",
... | identifier_body |
toInteger.d.ts | // AUTO-GENERATED: do not modify this file directly.
// If you need to make changes, modify generate-fp.ts (if necessary), then open a terminal in types/lodash/scripts, and do:
// npm run fp
type ToInteger =
/**
* Converts `value` to an integer.
*
* **Note:** This function is loosely based on [`ToIn... | *
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3');
* // => 3
*/
(value: any) => number;
declare const toInteger: ToInteger;
export = toInteger; | *
* _.toInteger(3);
* // => 3 | random_line_split |
dropck-eyepatch-extern-crate.rs | // Copyright 2016 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 ... |
extern crate dropck_eyepatch_extern_crate as other;
use other::{Dt,Dr,Pt,Pr,St,Sr};
fn main() {
use std::cell::RefCell;
struct CheckOnDrop(RefCell<String>, &'static str);
impl Drop for CheckOnDrop {
fn drop(&mut self) { assert_eq!(*self.0.borrow(), self.1); }
}
let c_long;
let (c, d... | // except according to those terms.
// run-pass
// aux-build:dropck_eyepatch_extern_crate.rs | random_line_split |
dropck-eyepatch-extern-crate.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
let c_long;
let (c, dt, dr, pt, pr, st, sr)
: (CheckOnDrop, Dt<_>, Dr<_>, Pt<_, _>, Pr<_>, St<_>, Sr<_>);
c_long = CheckOnDrop(RefCell::new("c_long".to_string()),
"c_long|pr|pt|dr|dt");
c = CheckOnDrop(RefCell::new("c".to_string()),
"c");
... | { assert_eq!(*self.0.borrow(), self.1); } | identifier_body |
dropck-eyepatch-extern-crate.rs | // Copyright 2016 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 ... | (&mut self) { assert_eq!(*self.0.borrow(), self.1); }
}
let c_long;
let (c, dt, dr, pt, pr, st, sr)
: (CheckOnDrop, Dt<_>, Dr<_>, Pt<_, _>, Pr<_>, St<_>, Sr<_>);
c_long = CheckOnDrop(RefCell::new("c_long".to_string()),
"c_long|pr|pt|dr|dt");
c = CheckOnDrop(RefCell:... | drop | identifier_name |
kafka_consumer.py | #!/usr/bin/env python
#
# It is recommended to run the kafka module against Python 2.7+. If missing
# 'kafka' read how to download it at:
# http://kafka-python.readthedocs.org/
#
# If missing 'avro' read how to download it at:
# https://avro.apache.org/docs/1.8.1/gettingstartedpython.html
#
# Binding to the topic spec... | for o, a in opts:
if o in ("-h", "--help"):
usage(sys.argv[0])
sys.exit()
elif o in ("-t", "--topic"):
required_cl += 1
kafka_topic = a
elif o in ("-T", "--produce-topic"):
kafka_produce_topic = a
elif o in ("-p", "--print"):
print_stdout = 1
elif o in ("-g"... | required_cl = 0
| random_line_split |
kafka_consumer.py | #!/usr/bin/env python
#
# It is recommended to run the kafka module against Python 2.7+. If missing
# 'kafka' read how to download it at:
# http://kafka-python.readthedocs.org/
#
# If missing 'avro' read how to download it at:
# https://avro.apache.org/docs/1.8.1/gettingstartedpython.html
#
# Binding to the topic spec... | required_cl = 0
for o, a in opts:
if o in ("-h", "--help"):
usage(sys.argv[0])
sys.exit()
elif o in ("-t", "--topic"):
required_cl += 1
kafka_topic = a
elif o in ("-T", "--produce-topic"):
kafka_produce_topic = a
elif o in ("-p", "--print"):
print_stdout = 1... | try:
opts, args = getopt.getopt(sys.argv[1:], "ht:T:pg:H:d:eu:as:", ["help", "topic=",
"group_id=", "host=", "decode-with-avro=", "earliest=", "url=",
"produce-topic=", "print=", "to-json-array=", "stats-interval="])
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # wi... | identifier_body |
kafka_consumer.py | #!/usr/bin/env python
#
# It is recommended to run the kafka module against Python 2.7+. If missing
# 'kafka' read how to download it at:
# http://kafka-python.readthedocs.org/
#
# If missing 'avro' read how to download it at:
# https://avro.apache.org/docs/1.8.1/gettingstartedpython.html
#
# Binding to the topic spec... |
if required_cl < 1:
print "ERROR: Missing required arguments"
usage(sys.argv[0])
sys.exit(1)
consumer = KafkaConsumer(kafka_topic, group_id=kafka_group_id, bootstrap_servers=[kafka_host], auto_offset_reset=topic_offset)
if kafka_produce_topic:
producer = KafkaProducer(bootstrap_servers=[kafka_host])
i... | assert False, "unhandled option" | conditional_block |
kafka_consumer.py | #!/usr/bin/env python
#
# It is recommended to run the kafka module against Python 2.7+. If missing
# 'kafka' read how to download it at:
# http://kafka-python.readthedocs.org/
#
# If missing 'avro' read how to download it at:
# https://avro.apache.org/docs/1.8.1/gettingstartedpython.html
#
# Binding to the topic spec... | (http_req, value):
try:
urllib2.urlopen(http_req, value)
except urllib2.HTTPError, err:
print "WARN: urlopen() returned HTTP error code:", err.code
sys.stdout.flush()
except urllib2.URLError, err:
print "WARN: urlopen() returned URL error reason:", err.reason
sys.stdout.flush()
def main():
try:
opts, a... | post_to_url | identifier_name |
method-ambig-one-trait-unknown-int-type.rs | // Copyright 2012-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-MI... | (&self) -> isize {2}
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just ... | foo | identifier_name |
method-ambig-one-trait-unknown-int-type.rs | // Copyright 2012-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-MI... |
}
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we cou... | {1} | identifier_body |
method-ambig-one-trait-unknown-int-type.rs | // Copyright 2012-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-MI... |
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just based on calling foo().... |
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
} | random_line_split |
small-enum-range-edge.rs | // Copyright 2013 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 ... |
// this is for the wrapping_add call below.
#![feature(core)]
/*!
* Tests the range assertion wraparound case in trans::middle::adt::load_discr.
*/
#[repr(u8)]
#[derive(Copy, Clone)]
enum Eu { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy, Clone)]
enum Es { Ls = -... | // except according to those terms.
| random_line_split |
small-enum-range-edge.rs | // Copyright 2013 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 ... | { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy, Clone)]
enum Es { Ls = -128, Hs = 127 }
static CLs: Es = Es::Ls;
static CHs: Es = Es::Hs;
pub fn main() {
assert_eq!((Eu::Hu as u8).wrapping_add(1), Eu::Lu as u8);
assert_eq!((Es::Hs as i8).wrapping_add(1), Es... | Eu | identifier_name |
small-enum-range-edge.rs | // Copyright 2013 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 ... | {
assert_eq!((Eu::Hu as u8).wrapping_add(1), Eu::Lu as u8);
assert_eq!((Es::Hs as i8).wrapping_add(1), Es::Ls as i8);
assert_eq!(CLu as u8, Eu::Lu as u8);
assert_eq!(CHu as u8, Eu::Hu as u8);
assert_eq!(CLs as i8, Es::Ls as i8);
assert_eq!(CHs as i8, Es::Hs as i8);
} | identifier_body | |
invalid_throw.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// 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 ap... | function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// Require CodeMirror
if (angular.isUndefined(window.CodeMirror)) {
throw Error('CodeMirror not found.'); // Use of throw is not allowed.
}
}
};
}]
); |
angular.module('oppia').directive('codemirrorMergeview', [ | random_line_split |
invalid_throw.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// 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 ap... |
}
};
}]
);
| {
throw Error('CodeMirror not found.'); // Use of throw is not allowed.
} | conditional_block |
hello_canvas.rs | //! Basic hello world example, drawing
//! to a canvas.
use ggez::event;
use ggez::graphics::{self, Color};
use ggez::{Context, GameResult};
use glam::*;
use std::env;
use std::path;
struct MainState {
text: graphics::Text,
canvas: graphics::Canvas,
frames: usize,
draw_with_canvas: bool,
}
impl MainS... | else {
path::PathBuf::from("./resources")
};
let cb = ggez::ContextBuilder::new("hello_canvas", "ggez").add_resource_path(resource_dir);
let (mut ctx, event_loop) = cb.build()?;
let state = MainState::new(&mut ctx)?;
event::run(ctx, event_loop, state)
}
| {
let mut path = path::PathBuf::from(manifest_dir);
path.push("resources");
path
} | conditional_block |
hello_canvas.rs | //! Basic hello world example, drawing
//! to a canvas.
use ggez::event;
use ggez::graphics::{self, Color};
use ggez::{Context, GameResult};
use glam::*;
use std::env;
use std::path;
struct MainState {
text: graphics::Text,
canvas: graphics::Canvas,
frames: usize,
draw_with_canvas: bool,
}
impl MainS... |
fn draw(&mut self, ctx: &mut Context) -> GameResult {
let dest_point = Vec2::new(10.0, 10.0);
if self.draw_with_canvas {
println!("Drawing with canvas");
graphics::clear(ctx, graphics::Color::from((64, 0, 0, 0)));
graphics::set_canvas(ctx, Some(&self.canvas));... | {
Ok(())
} | identifier_body |
hello_canvas.rs | //! Basic hello world example, drawing
//! to a canvas.
use ggez::event;
use ggez::graphics::{self, Color};
use ggez::{Context, GameResult};
use glam::*;
use std::env;
use std::path;
struct MainState {
text: graphics::Text,
canvas: graphics::Canvas,
frames: usize,
draw_with_canvas: bool,
}
impl MainS... | (
&mut self,
_ctx: &mut Context,
_keycode: ggez::event::KeyCode,
_keymod: ggez::event::KeyMods,
repeat: bool,
) {
if !repeat {
self.draw_with_canvas = !self.draw_with_canvas;
println!("Canvas on: {}", self.draw_with_canvas);
}
}
}
... | key_down_event | identifier_name |
hello_canvas.rs | //! Basic hello world example, drawing
//! to a canvas.
use ggez::event;
use ggez::graphics::{self, Color};
use ggez::{Context, GameResult};
use glam::*;
use std::env;
use std::path;
struct MainState {
text: graphics::Text,
canvas: graphics::Canvas,
frames: usize,
draw_with_canvas: bool,
}
impl MainS... | println!("Canvas on: {}", self.draw_with_canvas);
}
}
}
pub fn main() -> GameResult {
let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let mut path = path::PathBuf::from(manifest_dir);
path.push("resources");
path
} else {
pat... | repeat: bool,
) {
if !repeat {
self.draw_with_canvas = !self.draw_with_canvas; | random_line_split |
exportServer.py | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB 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 limitatio... | if len(sys.argv) > 1 and "port" in sys.argv[1]:
port = sys.argv[1].split("=")[1]
else:
port = 8083
try:
httpd = make_server('', int(port), application)
print('Serving on port %s...' % str(port))
httpd.serve_forever()
except KeyboardInterrupt:
print('Goodbye.') | conditional_block | |
exportServer.py | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB 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 limitatio... | def updateHTML(time, name, contact, status):
""" Keep a queue of last 10 exported rows """
if len(rowQueue) >= MAXROWS:
dc = rowQueue.pop(0)
rowQueue.append("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>" % (time, name, contact, status))
def htmlRows(environ, start_response):
start_resp... | random_line_split | |
exportServer.py | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB 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 limitatio... | (environ, start_response):
"""
The main WSGI application. Dispatch the current request to
the functions either "exportRows", the VoltDB export endpoint,
or to "htmlRows", the source static html of recent notifications.
If neither, call the `not_found` function.
"""
path = environ.get('PATH_... | application | identifier_name |
exportServer.py | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2016 VoltDB 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 limitatio... |
getFuncs = {
"htmlRows" : htmlRows,
"exportRows" : exportRows,
}
def application(environ, start_response):
"""
The main WSGI application. Dispatch the current request to
the functions either "exportRows", the VoltDB export endpoint,
or to "htmlRows", the source static html of recent notificat... | start_response('200 OK', [('Content-Type', 'text/html')])
if "QUERY_STRING" in environ:
row = parse_qs(environ["QUERY_STRING"])
processRow(row)
return [] | identifier_body |
form.py | """
This module implements the FormRequest class which is a more convenient class
(than Request) to generate Requests based on form data.
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root... | (self, *args, **kwargs):
formdata = kwargs.pop('formdata', None)
if formdata and kwargs.get('method') is None:
kwargs['method'] = 'POST'
super(FormRequest, self).__init__(*args, **kwargs)
if formdata:
items = formdata.items() if isinstance(formdata, dict) else f... | __init__ | identifier_name |
form.py | """
This module implements the FormRequest class which is a more convenient class
(than Request) to generate Requests based on form data.
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root... |
# Get form element from xpath, if not found, go up
if formxpath is not None:
nodes = root.xpath(formxpath)
if nodes:
el = nodes[0]
while True:
if el.tag == 'form':
return el
el = el.getparent()
if el is... | f = root.xpath('//form[@id="%s"]' % formid)
if f:
return f[0] | conditional_block |
form.py | """
This module implements the FormRequest class which is a more convenient class
(than Request) to generate Requests based on form data.
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root... | if formxpath is not None:
nodes = root.xpath(formxpath)
if nodes:
el = nodes[0]
while True:
if el.tag == 'form':
return el
el = el.getparent()
if el is None:
break
encoded = formxp... | if f:
return f[0]
# Get form element from xpath, if not found, go up | random_line_split |
form.py | """
This module implements the FormRequest class which is a more convenient class
(than Request) to generate Requests based on form data.
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root... | kwargs.setdefault('encoding', response.encoding)
if formcss is not None:
from parsel.csstranslator import HTMLTranslator
formxpath = HTMLTranslator().css_to_xpath(formcss)
form = _get_form(response, formname, formid, formnumber, formxpath)
formdata = _get_inputs... | def __init__(self, *args, **kwargs):
formdata = kwargs.pop('formdata', None)
if formdata and kwargs.get('method') is None:
kwargs['method'] = 'POST'
super(FormRequest, self).__init__(*args, **kwargs)
if formdata:
items = formdata.items() if isinstance(formdata, ... | identifier_body |
finding_if_prime.py | #!/usr/bin/python3
import math
import random
def finding_prime(number):
num=abs(number)
if num<4: return True
for x in range(2,num):
if num%x == 0:
return False
return True
def finding_prime_sqrt(number):
num=abs(number)
if num<4: return True
for x in range(2,int(math.sqrt(num))+1):
if number%x == 0:
... |
def test_finding_prime():
number1=17
number2=20
assert(finding_prime(number1)==True)
assert(finding_prime(number2)==False)
assert(finding_prime_sqrt(number1)==True)
assert(finding_prime_sqrt(number2)==False)
assert(finding_prime_fermat(number1)==True)
assert(finding_prime_fermat(number2)==False)
print('Tests... | if number<=102:
for a in range(2,number):
if pow(a,number-1,number)!=1:
return False
return True
else:
for i in range(100):
a=random.randint(2,number-1)
if pow(a,number-1,number)!=1:
return False
return True | identifier_body |
finding_if_prime.py | #!/usr/bin/python3
import math
import random
def finding_prime(number):
num=abs(number)
if num<4: return True
for x in range(2,num):
if num%x == 0:
return False
return True
def finding_prime_sqrt(number):
num=abs(number)
if num<4: return True
for x in range(2,int(math.sqrt(num))+1):
if number%x == 0:
... |
else:
for i in range(100):
a=random.randint(2,number-1)
if pow(a,number-1,number)!=1:
return False
return True
def test_finding_prime():
number1=17
number2=20
assert(finding_prime(number1)==True)
assert(finding_prime(number2)==False)
assert(finding_prime_sqrt(number1)==True)
assert(finding_prime_... | for a in range(2,number):
if pow(a,number-1,number)!=1:
return False
return True | conditional_block |
finding_if_prime.py | #!/usr/bin/python3
import math
import random
def | (number):
num=abs(number)
if num<4: return True
for x in range(2,num):
if num%x == 0:
return False
return True
def finding_prime_sqrt(number):
num=abs(number)
if num<4: return True
for x in range(2,int(math.sqrt(num))+1):
if number%x == 0:
return False
return True
def finding_prime_fermat(number):
... | finding_prime | identifier_name |
finding_if_prime.py | #!/usr/bin/python3
import math
import random
def finding_prime(number):
num=abs(number)
if num<4: return True
for x in range(2,num):
if num%x == 0:
return False
return True
def finding_prime_sqrt(number):
num=abs(number)
if num<4: return True
for x in range(2,int(math.sqrt(num))+1):
if number%x == 0:
... | test_finding_prime() | random_line_split | |
relative-mouse-state.rs | extern crate sdl2;
use sdl2::event::Event;
use sdl2::mouse::MouseButton;
use std::time::Duration;
pub fn | () {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let _window = video_subsystem.window("Mouse", 800, 600)
.position_centered()
.build()
.unwrap();
let mut events = sdl_context.event_pump().unwrap();
let mut state;
'runnin... | main | identifier_name |
relative-mouse-state.rs | extern crate sdl2;
use sdl2::event::Event;
use sdl2::mouse::MouseButton;
use std::time::Duration;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let _window = video_subsystem.window("Mouse", 800, 600)
.position_centered()
.buil... | } | } | random_line_split |
relative-mouse-state.rs | extern crate sdl2;
use sdl2::event::Event;
use sdl2::mouse::MouseButton;
use std::time::Duration;
pub fn main() | // get a mouse state using mouse_state() so as not to call
// relative_mouse_state() twice and get a false position reading
if events.mouse_state().is_mouse_button_pressed(MouseButton::Left) {
state = events.relative_mouse_state();
println!("Relative - X = {:?}, Y = {:?}"... | {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let _window = video_subsystem.window("Mouse", 800, 600)
.position_centered()
.build()
.unwrap();
let mut events = sdl_context.event_pump().unwrap();
let mut state;
'running: ... | identifier_body |
main.rs | use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let different_scores: HashMap<_, _... |
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0)
*count += 1;
}
println!("{:?}", map);
// It's possible to use different hasher than default one
} |
let text = "hello wonderful world world";
let mut map = HashMap::new(); | random_line_split |
main.rs | use std::collections::HashMap;
fn main() |
scores.entry(String::from("Blue")).or_insert(100);
scores.entry(String::from("Red")).or_insert(200);
println!("{:?}", scores);
let text = "hello wonderful world world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0)
... | {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let different_scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()... | identifier_body |
main.rs | use std::collections::HashMap;
fn | () {
let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
let teams = vec![String::from("Blue"), String::from("Yellow")];
let initial_scores = vec![10, 50];
let different_scores: HashMap<_, _> = teams.iter().zip(initial_scores.ite... | main | identifier_name |
test_rpc_util.py | """
Test rpc_util functions
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>'
__date__ = '8/28/15'
# Imports
# stdlib
import re
# third-party
from nose.tools import raises
# local
from doekbase.data_api import rpc_util
from thrift.Thrift import TType
class Metadata:
"""SAMPLE object for testing validation, etc.
... | (self, object_id=None, object_name=None, object_reference=None,
object_reference_versioned=None, type_string=None,
save_timestamp=None, version=None, saved_by=None,
workspace_id=None, workspace_name=None, object_checksum=None,
object_size=None, object_... | __init__ | identifier_name |
test_rpc_util.py | """
Test rpc_util functions
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>'
__date__ = '8/28/15'
# Imports
# stdlib
import re
# third-party
from nose.tools import raises
# local
from doekbase.data_api import rpc_util
from thrift.Thrift import TType
class Metadata:
"""SAMPLE object for testing validation, etc.
... | self.workspace_name = workspace_name
self.object_checksum = object_checksum
self.object_size = object_size
self.object_metadata = object_metadata
@raises(rpc_util.InvalidField)
def test_thrift_validate_str_fail():
rpc_util.thrift_validate(Metadata(object_id=12))
@raises(rpc_util.I... | random_line_split | |
test_rpc_util.py | """
Test rpc_util functions
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>'
__date__ = '8/28/15'
# Imports
# stdlib
import re
# third-party
from nose.tools import raises
# local
from doekbase.data_api import rpc_util
from thrift.Thrift import TType
class Metadata:
"""SAMPLE object for testing validation, etc.
... |
@raises(rpc_util.InvalidField)
def test_thrift_validate_int_fail():
rpc_util.thrift_validate(Metadata(workspace_id='hello'))
@raises(rpc_util.InvalidField)
def test_thrift_validate_int_double_fail():
rpc_util.thrift_validate(Metadata(workspace_id=3.5))
@raises(rpc_util.InvalidField)
def test_thrift_validate... | rpc_util.thrift_validate(Metadata(object_id=12)) | identifier_body |
host.rs | use std::convert::TryFrom;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use super::EndpointError;
use crate::ZmqError;
/// Represents a host address. Does not include the port, and may be either an
/// ip address or a domain name
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enu... | (s: String) -> Result<Self, Self::Error> {
if s.is_empty() {
return Err(EndpointError::Syntax("Host string should not be empty"));
}
if let Ok(addr) = s.parse::<Ipv4Addr>() {
return Ok(Host::Ipv4(addr));
}
// Attempt to parse ipv6 from either ::1 or [::1]... | try_from | identifier_name |
host.rs | use std::convert::TryFrom;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use super::EndpointError;
use crate::ZmqError;
/// Represents a host address. Does not include the port, and may be either an
/// ip address or a domain name
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enu... |
}
#[cfg(test)]
mod tests {
use super::*;
// These two tests on std are more for reference than any real test of
// functionality
#[test]
fn std_ipv6_parse() {
assert_eq!(Ipv6Addr::LOCALHOST, "::1".parse::<Ipv6Addr>().unwrap());
assert!("[::1]".parse::<Ipv6Addr>().is_err());
}
... | {
let s = s.to_string();
Self::try_from(s)
} | identifier_body |
host.rs | use std::convert::TryFrom;
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use super::EndpointError;
use crate::ZmqError;
/// Represents a host address. Does not include the port, and may be either an
/// ip address or a domain name
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enu... | let parsed_host = parsed_host.unwrap();
if let Host::Domain(_) = parsed_host {
continue;
}
panic!(
"Expected that \"{}\" would not parse as Ipv6 or Ipv4, but instead it parsed as {:?}",
invalid, parsed_host
);
... | continue;
} | random_line_split |
test_auto_TrackMerge.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..postproc import TrackMerge
def test_TrackMerge_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=... | output_map = dict(track_file=dict(),
)
outputs = TrackMerge.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey), value | identifier_body | |
test_auto_TrackMerge.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..postproc import TrackMerge
def | ():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
output_file=dict(argstr='%s',
position=-1,
usedefault=True,
),
terminal_output=dict(nohash=True,
),
track_files=... | test_TrackMerge_inputs | identifier_name |
test_auto_TrackMerge.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..postproc import TrackMerge
def test_TrackMerge_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=... | mandatory=True,
position=0,
),
)
inputs = TrackMerge.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_TrackMerge_outputs():
output_map = d... | terminal_output=dict(nohash=True,
),
track_files=dict(argstr='%s...', | random_line_split |
test_auto_TrackMerge.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..postproc import TrackMerge
def test_TrackMerge_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=... | for metakey, value in list(metadata.items()):
yield assert_equal, getattr(outputs.traits()[key], metakey), value | conditional_block | |
timeoutWith.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { isDate } from '../util/isDate';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeT... | <T, R> extends OuterSubscriber<T, R> {
private action: SchedulerAction<TimeoutWithSubscriber<T, R>> = null;
constructor(destination: Subscriber<T>,
private absoluteTimeout: boolean,
private waitFor: number,
private withObservable: ObservableInput<any>,
priva... | TimeoutWithSubscriber | identifier_name |
timeoutWith.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { isDate } from '../util/isDate';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeT... |
super._next(value);
}
/** @deprecated This is an internal implementation detail, do not use. */
_unsubscribe() {
this.action = null;
this.scheduler = null;
this.withObservable = null;
}
}
| {
this.scheduleTimeout();
} | conditional_block |
timeoutWith.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { async } from '../scheduler/async';
import { Observable } from '../Observable';
import { isDate } from '../util/isDate';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeT... | * 
*
* `timeoutWith` is a variation of `timeout` operator. It behaves exactly the same,
* still accepting as a first argument either a number or a Date, which control - respectively -
* when values of source Observable should be emitted or when it should complete.
*
* The only difference is t... | *
* <span class="informal">It's a version of `timeout` operator that let's you specify fallback Observable.</span>
* | random_line_split |
login.component.ts | import { Component, AfterViewInit, OnDestroy, NgZone } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Router } from '@angular/router';
import { AuthenticationService } from '../shared/services/authentication.service';
declare var gapi: any;
@Component({
selector: 'login',
templa... |
});
}
ngAfterViewInit() {
gapi.signin2.render(
'signIn',
{
'onSuccess': googleUser => {
this.authService.authenticate(googleUser);
},
'longtitle': true,
'width': 200
}
);
}
ngOnDestroy() {
this.authSub.unsubscribe();
}
}
| {
this.zone.run(() => this.router.navigate(['/']));
} | conditional_block |
login.component.ts | import { Component, AfterViewInit, OnDestroy, NgZone } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Router } from '@angular/router';
import { AuthenticationService } from '../shared/services/authentication.service';
declare var gapi: any;
@Component({
selector: 'login',
templa... | implements AfterViewInit, OnDestroy {
authSub: Subscription;
constructor(private router: Router,
private authService: AuthenticationService,
private zone: NgZone) {
this.authSub = this.authService.authenticationStream()
.subscribe(isAuthenticated => {
if (isAuthentica... | LoginComponent | identifier_name |
login.component.ts | import { Component, AfterViewInit, OnDestroy, NgZone } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Router } from '@angular/router';
import { AuthenticationService } from '../shared/services/authentication.service';
declare var gapi: any;
@Component({
selector: 'login',
templa... |
ngOnDestroy() {
this.authSub.unsubscribe();
}
}
| {
gapi.signin2.render(
'signIn',
{
'onSuccess': googleUser => {
this.authService.authenticate(googleUser);
},
'longtitle': true,
'width': 200
}
);
} | identifier_body |
login.component.ts | import { Component, AfterViewInit, OnDestroy, NgZone } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Router } from '@angular/router';
import { AuthenticationService } from '../shared/services/authentication.service';
declare var gapi: any;
@Component({
selector: 'login',
templa... | gapi.signin2.render(
'signIn',
{
'onSuccess': googleUser => {
this.authService.authenticate(googleUser);
},
'longtitle': true,
'width': 200
}
);
}
ngOnDestroy() {
this.authSub.unsubscribe();
}
} | ngAfterViewInit() { | random_line_split |
tests.py | #!/usr/bin/env python
# Michael Cohen <scudette@users.sourceforge.net>
#
# ******************************************************
# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$
# ******************************************************
#
# * This program is free software; you can redistribute it... |
def test02ReadingTests(self):
""" Test reading ranges """
## Note we assume the file is at least 100 bytes long...
self.fd.seek(0)
data = self.fd.read(100)
self.assertEqual(len(data),100, "Data length read does not agree with read - or file too short?")
self.assertE... | """ Test for valid size """
self.assert_(self.fd,"No fd found")
size=self.fd.size
## Go to the end:
self.fd.seek(0,2)
self.assert_(size != 0, "Size is zero")
self.assertEqual(self.fd.tell(),size,"Seek to end of file does not agree with size") | identifier_body |
tests.py | #!/usr/bin/env python
# Michael Cohen <scudette@users.sourceforge.net>
#
# ******************************************************
# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$
# ******************************************************
#
# * This program is free software; you can redistribute it... | pyflagsh.shell_execv(command="execute",
argv=["Load Data.Load Filesystem image",'case=%s' % self.test_case,
"iosource=test",
"fstype=%s" % self.fstype,
"mount_point=%s" % self.mount_poin... | conditional_block | |
tests.py | #!/usr/bin/env python
# Michael Cohen <scudette@users.sourceforge.net>
#
# ******************************************************
# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$
# ******************************************************
#
# * This program is free software; you can redistribute it... |
if self.fstype:
pyflagsh.shell_execv(command="execute",
argv=["Load Data.Load Filesystem image",'case=%s' % self.test_case,
"iosource=test",
"fstype=%s" % self.fstype,
... | "filename=%s" % ( self.test_file),
"offset=%s"%self.offset,
"TZ=%s" % self.TZ
]) | random_line_split |
tests.py | #!/usr/bin/env python
# Michael Cohen <scudette@users.sourceforge.net>
#
# ******************************************************
# Version: FLAG $Version: 0.87-pre1 Date: Thu Jun 12 00:48:38 EST 2008$
# ******************************************************
#
# * This program is free software; you can redistribute it... | (unittest.TestCase):
## Must be overridden
test_case = ""
test_file = ""
subsystem = "EWF"
fstype = "Sleuthkit"
offset = 0
mount_point = '/'
TZ="SYSTEM"
def setUp(self):
""" Load test Case"""
try:
pyflagsh.shell_execv(command="execute",
... | ScannerTest | identifier_name |
cksum.rs | #![crate_name = "cksum"]
#![feature(collections, core, old_io, old_path, rustc_private)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/... | Ok((crc, size)) => println!("{} {}", crc, size),
Err(err) => {
show_error!("{}", err);
return 2;
}
}
return 0;
}
let mut exit_code = 0;
for fname in files.iter() {
match cksum(fname.as_slice()) {
Ok((crc... | match cksum("-") { | random_line_split |
cksum.rs | #![crate_name = "cksum"]
#![feature(collections, core, old_io, old_path, rustc_private)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/... | (crc: u32, input: u8) -> u32 {
(crc << 8) ^ CRC_TABLE[((crc >> 24) as usize ^ input as usize) & 0xFF]
}
#[inline]
fn crc_final(mut crc: u32, mut length: usize) -> u32 {
while length != 0 {
crc = crc_update(crc, length as u8);
length >>= 8;
}
!crc
}
#[inline]
fn cksum(fname: &str) -> I... | crc_update | identifier_name |
cksum.rs | #![crate_name = "cksum"]
#![feature(collections, core, old_io, old_path, rustc_private)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <mg@ebfe.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/... | Ok(num_bytes) => {
for &b in bytes[..num_bytes].iter() {
crc = crc_update(crc, b);
}
size += num_bytes;
}
Err(IoError { kind: EndOfFile, .. }) => return Ok((crc_final(crc, size), size)),
Err(err) => retur... | {
let mut crc = 0u32;
let mut size = 0usize;
let mut stdin_buf;
let mut file_buf;
let rd = match fname {
"-" => {
stdin_buf = stdin_raw();
&mut stdin_buf as &mut Reader
}
_ => {
file_buf = try!(File::open(&Path::new(fname)));
&... | identifier_body |
early-vtbl-resolution.rs | // 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 http://opensource.org/licenses/MIT>, at your
// option. This file... | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | random_line_split | |
early-vtbl-resolution.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 ... | {
let _x: Option<f64> = foo_func(0);
} | identifier_body | |
early-vtbl-resolution.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 ... | { a: int }
pub fn main() {
let _x: Option<f64> = foo_func(0);
}
| A | identifier_name |
map.py | THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===========================================================================
# Imports
import sys, time, logging, os, datetime, math
import numpy as np
import scipy.optimize
import scipy.special
import scipy.ndimage
import pyfits
import p... |
if not p0 :
p0 = [n[0] / r_a[0], 1.5, 3., -5.] # Initial guess for the parameters
#p0 = [.5 * n[0] / r_a[0], 1.5, 3., -5., .5 * n[0] / r_a[0], 100., .5] # Initial guess for the parameters
fitter = pf.ChisquareFitter(fitfunc)
m = (n > 0.) * (nerr > 0.) * (r_a ... | fitfunc = lambda p, x: p[0] * x ** 0. * (1. + (x / p[1]) ** p[2]) ** ((0. + p[3]) / p[2])
#fitfunc = lambda p, x: p[0] * x ** 0. * (1. + (x / p[1]) ** p[2]) ** ((0. + p[3]) / p[2]) + p[4] / (np.exp(p[5] * (x - p[6])) + 1.) | conditional_block |
map.py | in dist.
Parameters
----------
ra : float/array
Right ascension of the coordinate.
dec : float/array
Declination of the coordinate.
"""
self.ra, self.dec = ra, dec
def dist(self, c) :
"""
Return the distance of the coordinate... | sky_mask = np.where((np.sqrt((sky_x - rmax) ** 2. + (sky_y - rmax) ** 2.) < rmax) * (np.sqrt((sky_x - rmax) ** 2. + (sky_y - rmax) ** 2.) > rmin), 1., 0.)
return sky_mask | random_line_split | |
map.py | THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===========================================================================
# Imports
import sys, time, logging, os, datetime, math
import numpy as np
import scipy.optimize
import scipy.special
import scipy.ndimage
import pyfits
import p... |
#---------------------------------------------------------------------------
class SkyCircle:
"""A circle on the sky."""
def __init__(self, c, r) :
"""
A circle on the sky.
Parameters
----------
coord : SkyCoord
Coordinates of the circle center (RA, De... | """
Return the distance of the coordinates in degree following the haversine formula,
see e.g. http://en.wikipedia.org/wiki/Great-circle_distance.
Parameters
----------
c : SkyCoord
Returns
-------
distance : float
Return the distance of the ... | identifier_body |
map.py | THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#===========================================================================
# Imports
import sys, time, logging, os, datetime, math
import numpy as np
import scipy.optimize
import scipy.special
import scipy.ndimage
import pyfits
import p... | (self, c) :
"""
Return the distance of the coordinates in degree following the haversine formula,
see e.g. http://en.wikipedia.org/wiki/Great-circle_distance.
Parameters
----------
c : SkyCoord
Returns
-------
distance : float
Return ... | dist | identifier_name |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | impl ::std::fmt::Display for NotInSchema {
fn fmt(&self, fmt : &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
write!(fmt, "Enum value or union discriminant {} was not present in the schema.", self.0)
}
}
impl ::std::error::Error for NotInSchema {
fn description(&self)... | random_line_split | |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | (&self, fmt : &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
write!(fmt, "Enum value or union discriminant {} was not present in the schema.", self.0)
}
}
impl ::std::error::Error for NotInSchema {
fn description(&self) -> &str {
"Enum value or union disriminant w... | fmt | identifier_name |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | ,
Error::Decode { ref description, .. } => write!(fmt, "{}", description),
Error::Io(ref io) => io.fmt(fmt),
}
}
}
impl ::std::error::Error for Error {
fn description(&self) -> &str {
match *self {
Error::Decode { ref description, .. } => description,
... | {
write!(fmt, "{} {}", description, detail)
} | conditional_block |
lib.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... |
pub fn bytes_to_words<'a>(bytes: &'a [u8]) -> &'a [Word] {
unsafe {
::std::slice::from_raw_parts(bytes.as_ptr() as *const Word, bytes.len() / 8)
}
}
pub fn words_to_bytes<'a>(words: &'a [Word]) -> &'a [u8] {
unsafe {
::std::slice::from_raw_parts(words.as_pt... | {
let mut result : Vec<Word> = Vec::with_capacity(length);
unsafe {
result.set_len(length);
let p : *mut u8 = result.as_mut_ptr() as *mut u8;
::std::ptr::write_bytes(p, 0u8, length * ::std::mem::size_of::<Word>());
}
return result;
} | identifier_body |
new-account-form.service.js | (function() {
"use strict";
angular.module("blocktrail.setup")
.factory("newAccountFormService", function($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) {
return new NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launc... | return self._launchService.getAccountInfo();
});
};
/**
* Error handler
* @param error
* @return { promise<string> }
* @private
*/
NewAccountFormService.prototype._errorHandler = function(error) {
var self = this;
var response;
va... |
return self._launchService.setAccountInfo(accountInfo)
.then(function() { | random_line_split |
new-account-form.service.js | (function() {
"use strict";
angular.module("blocktrail.setup")
.factory("newAccountFormService", function($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) {
return new NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launc... | ($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) {
var self = this;
self._$log = $log;
self._$http = $http;
self._$q = $q;
self._lodash = _;
self._cryptoJS = cryptoJS;
self._device = device || {};
self._CONFI... | NewAccountFormService | identifier_name |
new-account-form.service.js | (function() {
"use strict";
angular.module("blocktrail.setup")
.factory("newAccountFormService", function($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) {
return new NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launc... |
/**
* Register
* @param data
* @return { promise }
*/
NewAccountFormService.prototype.register = function(data) {
var self = this;
var postData = {
username: null,
email: data.email,
password: self._cryptoJS.SHA512(data.password).toStrin... | {
var self = this;
self._$log = $log;
self._$http = $http;
self._$q = $q;
self._lodash = _;
self._cryptoJS = cryptoJS;
self._device = device || {};
self._CONFIG = CONFIG;
self._launchService = launchService;
self._settingsService = setting... | identifier_body |
util.js | parseInt(ms, 10);
};
// Use these to help sort formats, higher is better.
var audioEncodingRanks = {
mp3: 1,
vorbis: 2,
aac: 3,
opus: 4,
flac: 5,
};
var videoEncodingRanks = {
'Sorenson H.283': 1,
'MPEG-4 Visual': 2,
'VP8': 3,
'VP9': 4,
'H.264': 5,
};
/**
* Sort formats from highest quality to... |
function audioScore(c) {
var abitrate = c.audioBitrate || 0;
var aenc = audioEncodingRanks[c.audioEncoding] || 0;
return abitrate + aenc / 10;
}
if (afeats === bfeats) {
if (ares === bres) {
var avbitrate = getBitrate(a);
var bvbitrate = getBitrate(b);
if (avbitrate === bvbitr... | {
if (c.bitrate) {
var s = c.bitrate.split('-');
return parseFloat(s[s.length - 1], 10);
} else {
return 0;
}
} | identifier_body |
util.js | parseFloat(s[s.length - 1], 10);
} else {
return 0;
}
}
function audioScore(c) {
var abitrate = c.audioBitrate || 0;
var aenc = audioEncodingRanks[c.audioEncoding] || 0;
return abitrate + aenc / 10;
}
if (afeats === bfeats) {
if (ares === bres) {
var avbitrate = getBitrate... | checkDone | identifier_name | |
util.js | parseInt(ms, 10);
};
// Use these to help sort formats, higher is better.
var audioEncodingRanks = {
mp3: 1,
vorbis: 2,
aac: 3,
opus: 4,
flac: 5,
};
var videoEncodingRanks = {
'Sorenson H.283': 1,
'MPEG-4 Visual': 2,
'VP8': 3,
'VP9': 4,
'H.264': 5,
};
/**
* Sort formats from highest quality to... |
var parsed = url.parse(link, true);
var id = parsed.query.v;
if (parsed.hostname === 'youtu.be' ||
(parsed.hostname === 'youtube.com' ||
parsed.hostname === 'www.youtube.com') && !id) {
var s = parsed.pathname.split('/');
id = s[s.length - 1];
}
if (!id) {
throw new Error('No video i... | {
return link;
} | conditional_block |
util.js | + parseInt(ms, 10);
};
// Use these to help sort formats, higher is better.
var audioEncodingRanks = {
mp3: 1,
vorbis: 2,
aac: 3,
opus: 4,
flac: 5,
};
var videoEncodingRanks = {
'Sorenson H.283': 1,
'MPEG-4 Visual': 2,
'VP8': 3,
'VP9': 4,
'H.264': 5,
};
/**
* Sort formats from highest quality ... | * There are a few type of video URL formats.
* - http://www.youtube.com/watch?v=VIDEO_ID
* - http://m.youtube.com/watch?v=VIDEO_ID
* - http://youtu.be/VIDEO_ID
* - http://www.youtube.com/v/VIDEO_ID
* - http://www.youtube.com/embed/VIDEO_ID
*
* @param {String} link
* @return {String}
*/
var idRegex = /^[a... |
/**
* Get video ID.
* | random_line_split |
issue-30079.rs | struct SemiPriv;
mod m1 {
struct Priv;
impl ::SemiPriv {
pub fn f(_: Priv) {} //~ WARN private type `m1::Priv` in public interface
//~^ WARNING hard error
}
impl Priv {
pub fn f(_: Priv) {} // ok
}
}
mod m2 {
struct Priv;
impl ::std::ops::Deref for ::SemiPriv {
... | {} | identifier_body | |
issue-30079.rs | struct | ;
mod m1 {
struct Priv;
impl ::SemiPriv {
pub fn f(_: Priv) {} //~ WARN private type `m1::Priv` in public interface
//~^ WARNING hard error
}
impl Priv {
pub fn f(_: Priv) {} // ok
}
}
mod m2 {
struct Priv;
impl ::std::ops::Deref for ::SemiPriv {
type Targe... | SemiPriv | identifier_name |
issue-30079.rs | struct SemiPriv;
mod m1 {
struct Priv;
impl ::SemiPriv {
pub fn f(_: Priv) {} //~ WARN private type `m1::Priv` in public interface
//~^ WARNING hard error
}
impl Priv {
pub fn f(_: Priv) {} // ok
}
}
mod m2 {
struct Priv;
impl ::std::ops::Deref for ::SemiPriv {
... | impl ::std::ops::Deref for Priv {
type Target = Priv; // ok
fn deref(&self) -> &Self::Target { unimplemented!() }
}
}
trait SemiPrivTrait {
type Assoc;
}
mod m3 {
struct Priv;
impl ::SemiPrivTrait for () {
type Assoc = Priv; //~ ERROR private type `m3::Priv` in public inter... | random_line_split | |
ErrorTable.tsx | /*
* Copyright 2018 Crown Copyright
*
* 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... | * limitations under the License.
*/
import * as React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { splitAt } from "ramda";
import ReactTable, { RowInfo } from "react-table";
import { AnyMarker, isStoredErrorMarker, StoredError } from "../types";
import Tooltip from "com... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | random_line_split |
index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3... |
(0, _createClass3.default)(EventListener, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.addListeners();
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
return (0, _reactAddonsShallowCompare2.default)({
props:... | {
(0, _classCallCheck3.default)(this, EventListener);
return (0, _possibleConstructorReturn3.default)(this, (EventListener.__proto__ || (0, _getPrototypeOf2.default)(EventListener)).apply(this, arguments));
} | identifier_body |
index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3... | (target, eventName, callback, options) {
if (supports.addEventListener) {
target.addEventListener.apply(target, getEventListenerArgs(eventName, callback, options));
} else if (supports.attachEvent) {
// IE8+ Support
target.attachEvent('on' + eventName, function () {
callback.call(target);
});
... | on | identifier_name |
index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3... | var prop = props[name];
var type = typeof prop === 'undefined' ? 'undefined' : (0, _typeof3.default)(prop);
var isObject = type === 'object';
var isFunction = type === 'function';
if (!isObject && !isFunction) {
return;
}
var capture = name.substr(-7).toLowerCase() === 'capture';
... | random_line_split | |
test_fs.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys | import uuid
import win32file
from winsys.tests.test_fs import utils
from winsys import fs
class TestFS (unittest.TestCase):
filenames = ["%d" % i for i in range (5)]
def setUp (self):
utils.mktemp ()
for filename in self.filenames:
with open (os.path.join (utils.TEST_ROOT, filename), "w"):
... | import tempfile
from winsys._compat import unittest | random_line_split |
test_fs.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import tempfile
from winsys._compat import unittest
import uuid
import win32file
from winsys.tests.test_fs import utils
from winsys import fs
class TestFS (unittest.TestCase):
filenames = ["%d" % i for i in range (5)]
def setUp (se... | raw_input ("Press enter...") | conditional_block | |
test_fs.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import tempfile
from winsys._compat import unittest
import uuid
import win32file
from winsys.tests.test_fs import utils
from winsys import fs
class TestFS (unittest.TestCase):
filenames = ["%d" % i for i in range (5)]
def setUp (se... |
def test_glob (self):
import glob
pattern = os.path.join (utils.TEST_ROOT, "*")
self.assertEquals (list (fs.glob (pattern)), glob.glob (pattern))
def test_listdir (self):
import os
fs_version = list (fs.listdir (utils.TEST_ROOT))
os_version = os.listdir (utils.TEST_ROOT)
self.assertEq... | utils.rmtemp () | identifier_body |
test_fs.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import tempfile
from winsys._compat import unittest
import uuid
import win32file
from winsys.tests.test_fs import utils
from winsys import fs
class TestFS (unittest.TestCase):
filenames = ["%d" % i for i in range (5)]
def | (self):
utils.mktemp ()
for filename in self.filenames:
with open (os.path.join (utils.TEST_ROOT, filename), "w"):
pass
def tearDown (self):
utils.rmtemp ()
def test_glob (self):
import glob
pattern = os.path.join (utils.TEST_ROOT, "*")
self.assertEquals (list (fs.glob (patt... | setUp | identifier_name |
zh.js | /*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'zh', {
button: {
title: '按鈕內容',
text: '顯示文字 (值)',
type: '類型',
typeBtn: '按鈕',
typeSbm: '送出',
| checkboxTitle: '核取方塊內容',
radioTitle: '選項按鈕內容',
value: '數值',
selected: '已選'
},
form: {
title: '表單內容',
menu: '表單內容',
action: '動作',
method: '方式',
encoding: '編碼'
},
hidden: {
title: '隱藏欄位內容',
name: '名稱',
value: '數值'
},
select: {
title: '選取欄位內容',
selectInfo: '選擇資訊',
op... | typeRst: '重設'
},
checkboxAndRadio: {
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.