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 |
|---|---|---|---|---|
server.py | """
Tornado websocket server
"""
import tornado.ioloop
import tornado.web
import tornado.websocket
import os
from threading import Thread
from modules import noise, anomaly, message, event
settings = {"static_path": os.path.join(os.path.dirname(__file__), "static")}
# Runt the audio level thread
Thread(target=noise.... | application.listen(5000)
tornado.ioloop.IOLoop.instance().start() | if __name__ == "__main__": | random_line_split |
server.py | """
Tornado websocket server
"""
import tornado.ioloop
import tornado.web
import tornado.websocket
import os
from threading import Thread
from modules import noise, anomaly, message, event
settings = {"static_path": os.path.join(os.path.dirname(__file__), "static")}
# Runt the audio level thread
Thread(target=noise.... | application.listen(5000)
tornado.ioloop.IOLoop.instance().start() | conditional_block | |
server.py | """
Tornado websocket server
"""
import tornado.ioloop
import tornado.web
import tornado.websocket
import os
from threading import Thread
from modules import noise, anomaly, message, event
settings = {"static_path": os.path.join(os.path.dirname(__file__), "static")}
# Runt the audio level thread
Thread(target=noise.... |
def on_message(self, message):
print("Received a message : " + message)
def on_close(self):
print("WebSocket closed")
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/event", EventHandler),
(r"/level", LevelHandler),
(r"/ws", WebSocketHandler)
], **s... | print("WebSocket Opened")
# Pass the object to different modules
# so that they can communicate with the dash
Thread(target=anomaly.anomaly_detection, args=(self, )).start()
Thread(target=message.speech_win, args=(self, )).start() | identifier_body |
mockimaplib.py | mockimaplib
>>> connection = mockimaplib.IMAP4_SSL(<host>)
>>> connection.login(<user>, <password>)
None
>>> connection.select("INBOX")
("OK", ... <mailbox length>)
# fetch commands specifying single uid or message id
# will try to get messages recorded in SPAM
>>> connection.uid(...)
<search query or fetch result>
# ... | for x, item in enumerate(self.spam[self._mailbox]):
if item["uid"] == m:
item["id"] = x + 1
messages.append(item)
break
except IndexError:
# message removed... | self.spam[self._mailbox][m - 1]["id"] = m
messages.append(self.spam[self._mailbox][m - 1])
except TypeError: | random_line_split |
mockimaplib.py | 0010101010001010101001010010000001@mail.example.com>\r\nSubject: spam1\r\nFrom: Mr. Gumby <gumby@example.com>\r\nTo: The nurse <nurse@example.com>\r\nContent-Type: text/plain; charset=ISO-8859-1\r\n\r\nNurse!\r\n\r\n\r\n",
"MIME-Version: 1.0\r\nReceived: by 10.140.91.199 with HTTP; Mon, 27 Jan 2014 13:52:47 -0800 (... | """args:
first: None
query: string with mailbox query (flags, date, uid, id, ...)
example: '2:15723 BEFORE 27-Jan-2014 FROM "gumby"'
result[1][0] -> "id_1 id_2 ... id_n"
"""
messages = self._get_messages(query)
ids = " ".join([str(item["id"]) for... | identifier_body | |
mockimaplib.py | mockimaplib
>>> connection = mockimaplib.IMAP4_SSL(<host>)
>>> connection.login(<user>, <password>)
None
>>> connection.select("INBOX")
("OK", ... <mailbox length>)
# fetch commands specifying single uid or message id
# will try to get messages recorded in SPAM
>>> connection.uid(...)
<search query or fetch result>
# ... | (self, value, arg):
try:
message = self.spam[self._mailbox][value - 1]
message_id = value
except TypeError:
for x, item in enumerate(self.spam[self._mailbox]):
if item["uid"] == value:
message = item
message_id =... | _fetch | identifier_name |
mockimaplib.py | imaplib
>>> connection = mockimaplib.IMAP4_SSL(<host>)
>>> connection.login(<user>, <password>)
None
>>> connection.select("INBOX")
("OK", ... <mailbox length>)
# fetch commands specifying single uid or message id
# will try to get messages recorded in SPAM
>>> connection.uid(...)
<search query or fetch result>
# retur... |
return ("OK", (("%s " % message_id, message[parts]), message["flags"]))
def _get_messages(self, query):
if query.strip().isdigit():
return [
self.spam[self._mailbox][int(query.strip()) - 1],
]
elif query[1:-1].strip().isdigit():
return [... | parts = "complete" | conditional_block |
customevent.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/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... |
self.detail.set(detail.get());
event.init_event(type_, can_bubble, cancelable);
}
}
impl CustomEventMethods for CustomEvent {
// https://dom.spec.whatwg.org/#dom-customevent-detail
fn Detail(&self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
// https://dom.spec.wh... | {
return;
} | conditional_block |
customevent.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/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... | (global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
... | Constructor | identifier_name |
customevent.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/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... | Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
unsafe { HandleValue::from_marked_location(&init.detail) }))
}
fn init_custom_event(&self,
type_: Atom,
... | type_: DOMString,
init: &CustomEventBinding::CustomEventInit)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global, | random_line_split |
customevent.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/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding... |
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool,
detail: HandleValue)
-> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail... | {
reflect_dom_object(box CustomEvent::new_inherited(),
global,
CustomEventBinding::Wrap)
} | identifier_body |
get_login_types.rs | //! [GET /_matrix/client/r0/login](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-login)
use ruma_api::ruma_api;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata {
description: "Gets the homeserver's supported login types to authenticate users. Clients should pick one of t... | () {
assert_eq!(
from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),
LoginType::Password,
);
}
}
| deserialize_login_type | identifier_name |
get_login_types.rs | //! [GET /_matrix/client/r0/login](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-login)
use ruma_api::ruma_api;
use serde::{Deserialize, Serialize};
ruma_api! {
metadata {
description: "Gets the homeserver's supported login types to authenticate users. Clients should pick one of t... | #[serde(rename = "m.login.token")]
Token,
}
#[cfg(test)]
mod tests {
use serde_json::{from_value as from_json_value, json};
use super::LoginType;
#[test]
fn deserialize_login_type() {
assert_eq!(
from_json_value::<LoginType>(json!({ "type": "m.login.password" })).unwrap(),... | random_line_split | |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async ... | <F: Foo>(f: F) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_where_clause_block<F>(f: F) -> impl Future<Output = ()>
where
F: Foo,
{
async move { f.foo() }
}
pub fn call_impl_trait_block(f: impl Foo) -> impl Future<Output = ()> {
async move { f.foo() }
}
pub fn call_with_ref_bloc... | call_generic_bound_block | identifier_name |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async ... | pub async fn call_with_ref(f: &impl Foo) {
f.foo()
}
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
... | pub async fn call_impl_trait(f: impl Foo) {
f.foo()
}
| random_line_split |
generics-and-bounds.rs | // build-pass (FIXME(62277): could be check-pass?)
// edition:2018
// compile-flags: --crate-type lib
use std::future::Future;
pub async fn simple_generic<T>() {}
pub trait Foo {
fn foo(&self) {}
}
struct FooType;
impl Foo for FooType {}
pub async fn call_generic_bound<F: Foo>(f: F) {
f.foo()
}
pub async ... |
pub fn async_fn_with_same_generic_params_unifies() {
let mut a = call_generic_bound(FooType);
a = call_generic_bound(FooType);
let mut b = call_where_clause(FooType);
b = call_where_clause(FooType);
let mut c = call_impl_trait(FooType);
c = call_impl_trait(FooType);
let f_one = FooType;... | {
f.foo()
} | identifier_body |
analysis-util.ts | poiTypes from './poi-types';
const walk = require('acorn/dist/walk');
/**
* Finds specified function identifier and returns an array of AST nodes that
* they are located in
*
* @param id the identifier that is being searched for
* @param acornTree abstract syntax tree
*/
export function findCallee(id: string, ... |
}
/**
* Returns a the string argument and 'Dynamic', indicating
* that the argument is dynamic
*
* @param node the AST node containing the string argument
*/
export function getArgument(node: Node): string|null {
if (node.type === 'Literal' && node.value) {
const ioMod = node.value.toString();
return i... | {
return requiredModules;
} | conditional_block |
analysis-util.ts | as poiTypes from './poi-types';
const walk = require('acorn/dist/walk');
/**
* Finds specified function identifier and returns an array of AST nodes that
* they are located in
*
* @param id the identifier that is being searched for
* @param acornTree abstract syntax tree
*/
export function findCallee(id: strin... | (e: NewExpression) {
if (e.callee.type === 'Identifier' && e.callee.name === id) {
calleeUsages.push(e);
}
}
});
return calleeUsages;
}
/**
* Finds specified object identifier and returns an array of AST nodes that
* they are located in
*
* @param name the name of the object
* @param a... | NewExpression | identifier_name |
analysis-util.ts | poiTypes from './poi-types';
const walk = require('acorn/dist/walk');
/**
* Finds specified function identifier and returns an array of AST nodes that
* they are located in
*
* @param id the identifier that is being searched for
* @param acornTree abstract syntax tree
*/
export function findCallee(id: string, ... | return locationsOfPropAccesses;
}
/**
* Locates dynamic accesses of an object and its properties given AST nodes
*
* @param nodes the nodes of an AST that contain the object with the property
*/
export function locateIndexPropertyAccesses(nodes: MemberExpression[]):
Position[] {
const indexPropsPos: Posit... | {
const locationsOfPropAccesses: Position[] = [];
nodes.forEach((n) => {
const pos: Position = getPosition(n);
// Direct access to property
if (n.property.type === 'Identifier') {
if (n.property.name === property) {
locationsOfPropAccesses.push(pos);
}
// Indexing into object... | identifier_body |
analysis-util.ts | as poiTypes from './poi-types';
const walk = require('acorn/dist/walk');
/**
* Finds specified function identifier and returns an array of AST nodes that
* they are located in
*
* @param id the identifier that is being searched for
* @param acornTree abstract syntax tree
*/
export function findCallee(id: strin... | });
return locationsOfPropAccesses;
}
/**
* Locates dynamic accesses of an object and its properties given AST nodes
*
* @param nodes the nodes of an AST that contain the object with the property
*/
export function locateIndexPropertyAccesses(nodes: MemberExpression[]):
Position[] {
const indexPropsPos:... | if (arg === property) {
locationsOfPropAccesses.push(pos);
}
} | random_line_split |
playerset.py | from PyQt5.QtCore import QObject, pyqtSignal
from model.player import Player
class Playerset(QObject):
"""
Wrapper for an id->Player map
Used to lookup players either by id or by login.
"""
playerAdded = pyqtSignal(object)
playerRemoved = pyqtSignal(object)
def __init__(self):
Q... |
if isinstance(item, str):
return self._logins[item]
raise TypeError
def __len__(self):
return len(self._players)
def __iter__(self):
return iter(self._players)
# We need to define the below things - QObject
# doesn't allow for Mapping mixin
def keys(se... | return self._players[item] | conditional_block |
playerset.py | from PyQt5.QtCore import QObject, pyqtSignal
from model.player import Player
class Playerset(QObject):
"""
Wrapper for an id->Player map
Used to lookup players either by id or by login.
"""
playerAdded = pyqtSignal(object)
playerRemoved = pyqtSignal(object)
def __init__(self):
Q... | (self):
return self._players.items()
def get(self, item, default=None):
try:
return self[item]
except KeyError:
return default
def __contains__(self, item):
try:
self[item]
return True
except KeyError:
return F... | items | identifier_name |
playerset.py | from PyQt5.QtCore import QObject, pyqtSignal
from model.player import Player
class Playerset(QObject):
"""
Wrapper for an id->Player map
Used to lookup players either by id or by login.
"""
playerAdded = pyqtSignal(object)
playerRemoved = pyqtSignal(object)
def __init__(self):
Q... | # Login -> Player map
self._logins = {}
def __getitem__(self, item):
if isinstance(item, int):
return self._players[item]
if isinstance(item, str):
return self._logins[item]
raise TypeError
def __len__(self):
return len(self._players)
... | random_line_split | |
playerset.py | from PyQt5.QtCore import QObject, pyqtSignal
from model.player import Player
class Playerset(QObject):
"""
Wrapper for an id->Player map
Used to lookup players either by id or by login.
"""
playerAdded = pyqtSignal(object)
playerRemoved = pyqtSignal(object)
def __init__(self):
Q... |
def getID(self, name):
if name in self:
return self[name].id
return -1
def __setitem__(self, key, value):
if not isinstance(key, int) or not isinstance(value, Player):
raise TypeError
if key in self: # disallow overwriting existing players
... | try:
self[item]
return True
except KeyError:
return False | identifier_body |
Ew_monthly.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 09:37:33 2018
@author: tih
"""
import os
import sys
from DataAccess import DownloadData
def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1):
"""
This function downloads monthly ETmonitor data
Keyword arguments:
... | if __name__ == '__main__':
main(sys.argv) |
# Download data
DownloadData(Dir, Startdate, Enddate, latlim, lonlim, Type, Waitbar)
| random_line_split |
Ew_monthly.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 09:37:33 2018
@author: tih
"""
import os
import sys
from DataAccess import DownloadData
def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1):
|
if __name__ == '__main__':
main(sys.argv) | """
This function downloads monthly ETmonitor data
Keyword arguments:
Dir -- 'C:/file/to/path/'
Startdate -- 'yyyy-mm-dd'
Enddate -- 'yyyy-mm-dd'
latlim -- [ymin, ymax] (values must be between -60 and 70)
lonlim -- [xmin, xmax] (values must be between -180 and 180)
"""
print '\nDown... | identifier_body |
Ew_monthly.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 09:37:33 2018
@author: tih
"""
import os
import sys
from DataAccess import DownloadData
def main(Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1):
"""
This function downloads monthly ETmonitor data
Keyword arguments:
... | main(sys.argv) | conditional_block | |
Ew_monthly.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 03 09:37:33 2018
@author: tih
"""
import os
import sys
from DataAccess import DownloadData
def | (Dir, Startdate='', Enddate='', latlim=[-60, 70], lonlim=[-180, 180], Waitbar = 1):
"""
This function downloads monthly ETmonitor data
Keyword arguments:
Dir -- 'C:/file/to/path/'
Startdate -- 'yyyy-mm-dd'
Enddate -- 'yyyy-mm-dd'
latlim -- [ymin, ymax] (values must be between -60 and 70)
... | main | identifier_name |
path_mapped_compiler_host.d.ts | import { AngularCompilerOptions, ModuleMetadata } from '@angular/tsc-wrapped';
import * as ts from 'typescript';
import { CompilerHost, CompilerHostContext } from './compiler_host';
/**
* This version of the AotCompilerHost expects that the program will be compiled
* and executed with a "path mapped" directory struct... | extends CompilerHost {
constructor(program: ts.Program, options: AngularCompilerOptions, context: CompilerHostContext);
getCanonicalFileName(fileName: string): string;
moduleNameToFileName(m: string, containingFile: string): string;
/**
* We want a moduleId that will appear in import statements in... | PathMappedCompilerHost | identifier_name |
path_mapped_compiler_host.d.ts | import { AngularCompilerOptions, ModuleMetadata } from '@angular/tsc-wrapped'; | * and executed with a "path mapped" directory structure, where generated files
* are in a parallel tree with the sources, and imported using a `./` relative
* import. This requires using TS `rootDirs` option and also teaching the module
* loader what to do.
*/
export declare class PathMappedCompilerHost extends Co... | import * as ts from 'typescript';
import { CompilerHost, CompilerHostContext } from './compiler_host';
/**
* This version of the AotCompilerHost expects that the program will be compiled | random_line_split |
211_add_and_search_word-data_structure_design.py | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
... | (object):
class TrieNode(object):
def __init__(self):
self.leaves = {}
self.nil = False
def __init__(self):
"""
initialize your data structure here.
"""
self.root = self.TrieNode()
def addWord(self, word):
"""
Adds a word into... | WordDictionary | identifier_name |
211_add_and_search_word-data_structure_design.py | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
... |
def searchTail(self, tail, loc):
if tail == '':
return loc.nil
for i, c in enumerate(tail):
if c == '.':
if loc.leaves == {}:
return False
else:
for leaf in loc.leaves:
if self.s... | """
Adds a word into the data structure.
:type word: str
:rtype: void
"""
loc = self.root
for c in word:
if c not in loc.leaves:
loc.leaves[c] = self.TrieNode()
loc = loc.leaves[c]
loc.nil = True | identifier_body |
211_add_and_search_word-data_structure_design.py | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
... |
elif c in loc.leaves:
loc = loc.leaves[c]
else:
return False
return loc.nil
def search(self, word):
"""
Returns if the word is in the data structure. A word could
contain the dot character '.' to represent any one letter.
... | for leaf in loc.leaves:
if self.searchTail(tail[i + 1:], loc.leaves[leaf]):
return True
return False | conditional_block |
211_add_and_search_word-data_structure_design.py | """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing
only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
... | You should be familiar with how a Trie works. If not, please work on this
problem: Implement Trie (Prefix Tree) first.
"""
class WordDictionary(object):
class TrieNode(object):
def __init__(self):
self.leaves = {}
self.nil = False
def __init__(self):
"""
initiali... | You may assume that all words are consist of lowercase letters a-z.
| random_line_split |
ScanGrid.ts | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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... |
values[i][j] = grid[i][j] + max;
}
}
return values[m-1][n-1];
}
} | {
max = c;
this._path[i][j-1] = MOVES.VERTICAL;
} | conditional_block |
ScanGrid.ts | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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... |
{
protected _path: Array<Array<number>> = new Array<Array<number>>(); // (optional) path associated with maximum-sum path
constructor()
{
// empty
}
/**
* Return a reference to an optimal path after a call to scan()
*
* @return Array<number> Path represented as a sequence ... | ScanGrid | identifier_name |
ScanGrid.ts | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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... |
/**
* Return a reference to an optimal path after a call to scan()
*
* @return Array<number> Path represented as a sequence of moves from the MOVES enum. This is currently a placeholder and will be implemented in the future
*/
public get getPath(): Array<number>
{
// tmmporary - th... | {
// empty
} | identifier_body |
ScanGrid.ts | /**
* Copyright 2016 Jim Armstrong (www.algorithmist.net)
*
* 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... | } | random_line_split | |
shootout-binarytrees.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// |
extern mod extra;
use std::iter::range_step;
use extra::future::Future;
use extra::arena::TypedArena;
enum Tree<'a> {
Nil,
Node(&'a Tree<'a>, &'a Tree<'a>, int)
}
fn item_check(t: &Tree) -> int {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
}
fn bottom_u... | // 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 may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
shootout-binarytrees.rs | // Copyright 2012-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-MI... | () {
let args = std::os::args();
let n = if std::os::getenv("RUST_BENCH").is_some() {
17
} else if args.len() <= 1u {
8
} else {
from_str(args[1]).unwrap()
};
let min_depth = 4;
let max_depth = if min_depth + 2 > n {min_depth + 2} else {n};
{
let arena = ... | main | identifier_name |
shootout-binarytrees.rs | // Copyright 2012-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-MI... |
fn bottom_up_tree<'r>(arena: &'r TypedArena<Tree<'r>>, item: int, depth: int)
-> &'r Tree<'r> {
if depth > 0 {
arena.alloc(Node(bottom_up_tree(arena, 2 * item - 1, depth - 1),
bottom_up_tree(arena, 2 * item, depth - 1),
item))
} else ... | {
match *t {
Nil => 0,
Node(l, r, i) => i + item_check(l) - item_check(r)
}
} | identifier_body |
smap_out_parser_json.py | """
Authors: Jeremy Haugen, UCLA, Anthony Nguyen, UCLA
Created: June 2015
Copyright notice in LICENSE file
This file is used to take the raw files generated by
the SAM, which are in CSV format and processes it into
json format. Then it will contact the sMAP server and
upload the json data into sMAP
"""
import uuid_... | if file.split(".")[-1] == "txt":
#print file
parse(file) | conditional_block | |
smap_out_parser_json.py | """
Authors: Jeremy Haugen, UCLA, Anthony Nguyen, UCLA
Created: June 2015
Copyright notice in LICENSE file
This file is used to take the raw files generated by
the SAM, which are in CSV format and processes it into
json format. Then it will contact the sMAP server and
upload the json data into sMAP
"""
import uuid_... |
def parse(file):
op_fname = "smap_" + os.path.basename(file).split(".")[0] + ".json"
if os.path.isfile(op_fname):
print "skipping",op_fname
return
else:
print "processing",op_fname
with open(file) as f, open(op_fname , "w+") as op:
j = 0
data = {}
for line in ... | args = "/usr/bin/curl -v -XPOST -d @"+filename + " -H \"Content-Type: application/json\" http://128.97.93.240:8079/add/mHRzALUD7OtL9TFi0MbJDm6mKWdA2DJp5wJT"
#print args
p = subprocess.Popen(args, shell=True) | identifier_body |
smap_out_parser_json.py | """
Authors: Jeremy Haugen, UCLA, Anthony Nguyen, UCLA
Created: June 2015
Copyright notice in LICENSE file
This file is used to take the raw files generated by | the SAM, which are in CSV format and processes it into
json format. Then it will contact the sMAP server and
upload the json data into sMAP
"""
import uuid_gen
import subprocess
import time
import json
import os
def curl_file_smap(filename):
#args = ["curl", "-XPOST", "-d", "@"+filename, '-H \"Content-Type: appli... | random_line_split | |
smap_out_parser_json.py | """
Authors: Jeremy Haugen, UCLA, Anthony Nguyen, UCLA
Created: June 2015
Copyright notice in LICENSE file
This file is used to take the raw files generated by
the SAM, which are in CSV format and processes it into
json format. Then it will contact the sMAP server and
upload the json data into sMAP
"""
import uuid_... | (filename):
#args = ["curl", "-XPOST", "-d", "@"+filename, '-H \"Content-Type: application/json\"', "http://128.97.93.240:8079/add/mHRzALUD7OtL9TFi0MbJDm6mKWdA2DJp5wJT"]
args = "/usr/bin/curl -v -XPOST -d @"+filename + " -H \"Content-Type: application/json\" http://128.97.93.240:8079/add/mHRzALUD7OtL9TFi0MbJDm... | curl_file_smap | identifier_name |
amp-3q-player.js | /**
* Copyright 2017 The AMP HTML 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 require... | () {
return true;
}
/** @override */
showControls() {
this.sdnPostMessage_('showControlbar');
}
/** @override */
hideControls() {
this.sdnPostMessage_('hideControlbar');
}
};
AMP.registerElement('amp-3q-player', Amp3QPlayer);
| isInteractive | identifier_name |
amp-3q-player.js | /**
* Copyright 2017 The AMP HTML 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 require... |
/** @override */
mute() {
this.sdnPostMessage_('mute');
}
/** @override */
unmute() {
this.sdnPostMessage_('unmute');
}
/** @override */
supportsPlatform() {
return true;
}
/** @override */
isInteractive() {
return true;
}
/** @override */
showControls() {
this.sdnP... | {
this.sdnPostMessage_('pause');
} | identifier_body |
amp-3q-player.js | /**
* Copyright 2017 The AMP HTML 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 require... |
sdnPostMessage_(message) {
this.playerReadyPromise_.then(() => {
if (this.iframe_ && this.iframe_.contentWindow) {
this.iframe_.contentWindow./*OK*/postMessage(message, '*');
}
});
}
// VideoInterface Implementation. See ../src/video-interface.VideoInterface
/** @override */
play... | break;
}
} | random_line_split |
amp-3q-player.js | /**
* Copyright 2017 The AMP HTML 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 require... |
const data = isObject(event.data) ? event.data : tryParseJson(event.data);
if (data === undefined) {
return;
}
switch (data.data) {
case 'ready':
this.element.dispatchCustomEvent(VideoEvents.LOAD);
this.playerReadyResolver_();
break;
case 'playing':
t... | {
if (event.source != this.iframe_.contentWindow) {
return;
}
} | conditional_block |
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/. */
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(nonzero)]
#![fea... | pub mod traversal;
pub mod webrender_helpers;
pub mod wrapper;
// For unit tests:
pub use fragment::Fragment;
pub use fragment::SpecificFragmentInfo; | mod table_rowgroup;
mod table_wrapper;
mod text; | random_line_split |
te.js | $.extend(window.lang_te, {
"rate_title": "ఈ అనువర్తనాన్ని రేట్ చేయండి", | "rate_star5": "ప్రేమించాను",
"rate_NOSUBMIT": "లేదు, ధన్యవాదాలు",
"rate_SUBMIT": "సమర్పించు",
"rate_SUBMITLATER": "తర్వాత",
"rate_messageTitle": "చిన్న సమీక్షను వ్రాయండి",
"rate_thanks": "అభిప్రాయానికి ధన్యవాదాలు",
"rate_FINISH": "ముగించు",
"rate_placeholder": "నువ్వు ఏమని అనుకుంటున్నావో మాకు చెప్పు",
}); | "rate_star1": "అది అసహ్యించుకుంది",
"rate_star2": "దీన్ని ఇష్టపడలేదు",
"rate_star3": "ఇది సరే",
"rate_star4": "అది నచ్చింది", | random_line_split |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[se... |
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c, 's, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanReplySendMessage for M
where
M: ToMessageId + ToSourceChat,
{
fn text_reply<'c, 's, T>(&self, text: T) -> SendMessage<'s>
wh... | {
SendMessage::new(self, text)
} | identifier_body |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[se... | pub fn new<C, T>(chat: C, text: T) -> Self
where
C: ToChatRef,
T: Into<Cow<'s, str>>,
{
SendMessage {
chat_id: chat.to_chat_ref(),
text: text.into(),
parse_mode: None,
disable_web_page_preview: false,
disable_notification: f... | impl<'s> SendMessage<'s> { | random_line_split |
send_message.rs | use std::borrow::Cow;
use std::ops::Not;
use crate::requests::*;
use crate::types::*;
/// Use this method to send text messages.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
#[must_use = "requests do nothing unless sent"]
pub struct SendMessage<'s> {
chat_id: ChatRef,
text: Cow<'s, str>,
#[se... | <'s, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>,
{
SendMessage::new(self, text)
}
}
/// Reply with text message.
pub trait CanReplySendMessage {
fn text_reply<'c, 's, T>(&self, text: T) -> SendMessage<'s>
where
T: Into<Cow<'s, str>>;
}
impl<M> CanRepl... | text | identifier_name |
cafe-details.component.ts | import {
Component,
Input, |
import {CafeDetails} from "./cafe-details";
import {CafeDetailsService} from "./cafe-details.service";
@Component({
selector: 'cafe-details',
template:`
<div *ngIf="synced">
<h2>{{cafeDetails.name}} details!</h2>
<div><label>id: </label>{{cafeDetails.id}}</div>
<div>
... | OnInit
} from 'angular2/core';
import {RouteParams} from 'angular2/router'; | random_line_split |
cafe-details.component.ts | import {
Component,
Input,
OnInit
} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {CafeDetails} from "./cafe-details";
import {CafeDetailsService} from "./cafe-details.service";
@Component({
selector: 'cafe-details',
template:`
<div *ngIf="synced">
<h... | () {
const id = parseInt(this._routeParams.get('id'));
this.synced = false;
this._cafeDetailsService.getCafeDetailsSlowly(id - 1)
.then((cafeDetails) => {
this.cafeDetails = cafeDetails;
this.synced = true;
});
}
} | ngOnInit | identifier_name |
download_action.tsx | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* 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 agr... | return (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
this.clearErrors();
if (vm.pipeline.isValid()) {
vm.preview(vnode.attrs.pluginId(), true).then((result) => {
result.do((res) => {
const name = result.header("content-disposition")!.replace(/^... |
handleDownload(vnode: m.Vnode<Attrs>) {
const vm = vnode.attrs.vm; | random_line_split |
download_action.tsx | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* 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 agr... |
};
}
clearErrors() {
this.globalError = Stream();
this.globalErrorDetail = Stream();
}
}
| {
this.globalError("Please fix the validation errors above");
} | conditional_block |
download_action.tsx | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* 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 agr... | extends MithrilComponent<Attrs> {
private globalError: Stream<string> = Stream();
private globalErrorDetail: Stream<Errors> = Stream();
view(vnode: m.Vnode<Attrs>) {
return <div class={css.downloadAction}>
<ServerErrors css={css} message={this.globalError} details={this.globalErrorDetail}/>
<Pr... | DownloadAction | identifier_name |
questions.service.ts | import { Injectable } from '@angular/core';
import { Question } from '../classes/question';
@Injectable()
export class QuestionsService {
constructor() { }
questions: Question[] = [
{ "id": 1,
"title": "Откуда деньги у Навального?",
"date": new Date(2017, 7, 10),//'10.08.2017',
"answers": 3,
"rat... | }
getListByDate(){
return this.questions.sort((a, b)=>{
return b.date > a.date ? 1 : -1;
});
}
getListUnanswered(){
return this.questions.filter((q)=>{return q.answers == 0});
}
updateQuestion(id){
let index = this.questions.findIndex((q) => q.id == id);
this.questions[index].answers ++;
}... | random_line_split | |
questions.service.ts | import { Injectable } from '@angular/core';
import { Question } from '../classes/question';
@Injectable()
export class QuestionsService {
constructor() { }
questions: Question[] = [
{ "id": 1,
"title": "Откуда деньги у Навального?",
"date": new Date(2017, 7, 10),//'10.08.2017',
"answers": 3,
"rat... | identifier_body | ||
questions.service.ts | import { Injectable } from '@angular/core';
import { Question } from '../classes/question';
@Injectable()
export class QuestionsService {
| () { }
questions: Question[] = [
{ "id": 1,
"title": "Откуда деньги у Навального?",
"date": new Date(2017, 7, 10),//'10.08.2017',
"answers": 3,
"rating": 80,
"views": 700 },
{ "id": 2,
"title": "Что делать с Кавказом?",
"date": new Date(2017, 7, 5),//'5.08.2017',
"answers": 3,
"ra... | constructor | identifier_name |
railforest_weinsa.py | #!/usr/bin/env python
# UPE Programming competiton 2015-11-1 "railforest" solution by Avi Weinstock
import re
import sys
INFINITY = float('inf')
line_to_ints = lambda line: [int(x, 10) for x in re.split(' *', line)]
def solver(width, height, grid):
prevs = [[0, list()] for _ in range(width)]
for (y, line) in... |
return solution
def main():
lines = sys.stdin.read().split('\n')
(height, width) = line_to_ints(lines[0])
#print(height,width)
grid = [line_to_ints(line) for line in lines[1:height+1]]
print(solver(width, height, grid))
if __name__ == '__main__':
main()
| solution = -1 | conditional_block |
railforest_weinsa.py | #!/usr/bin/env python
# UPE Programming competiton 2015-11-1 "railforest" solution by Avi Weinstock
import re
import sys
INFINITY = float('inf')
line_to_ints = lambda line: [int(x, 10) for x in re.split(' *', line)]
def solver(width, height, grid):
prevs = [[0, list()] for _ in range(width)]
for (y, line) in... | ():
lines = sys.stdin.read().split('\n')
(height, width) = line_to_ints(lines[0])
#print(height,width)
grid = [line_to_ints(line) for line in lines[1:height+1]]
print(solver(width, height, grid))
if __name__ == '__main__':
main()
| main | identifier_name |
railforest_weinsa.py | #!/usr/bin/env python
# UPE Programming competiton 2015-11-1 "railforest" solution by Avi Weinstock
import re
import sys
INFINITY = float('inf')
line_to_ints = lambda line: [int(x, 10) for x in re.split(' *', line)]
def solver(width, height, grid):
prevs = [[0, list()] for _ in range(width)]
for (y, line) in... |
if __name__ == '__main__':
main()
| lines = sys.stdin.read().split('\n')
(height, width) = line_to_ints(lines[0])
#print(height,width)
grid = [line_to_ints(line) for line in lines[1:height+1]]
print(solver(width, height, grid)) | identifier_body |
railforest_weinsa.py | #!/usr/bin/env python
# UPE Programming competiton 2015-11-1 "railforest" solution by Avi Weinstock
import re
import sys
INFINITY = float('inf')
line_to_ints = lambda line: [int(x, 10) for x in re.split(' *', line)]
def solver(width, height, grid):
prevs = [[0, list()] for _ in range(width)]
for (y, line) in... | return solution
def main():
lines = sys.stdin.read().split('\n')
(height, width) = line_to_ints(lines[0])
#print(height,width)
grid = [line_to_ints(line) for line in lines[1:height+1]]
print(solver(width, height, grid))
if __name__ == '__main__':
main() | solution = min([x for (x,_) in prevs])
if solution == INFINITY:
solution = -1 | random_line_split |
base.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/. */
use std::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we shoul... |
pub fn test_image_bin() -> ~[u8] {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, tr... |
static TEST_IMAGE: [u8, ..4962] = include_bin!("test.jpeg"); | random_line_split |
base.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/. */
use std::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we shoul... |
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_image::ImageU8(image) => {
assert!(image.depth == 4);
... | {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
} | identifier_body |
base.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/. */
use std::vec;
use stb_image = stb_image::image;
// FIXME: Images must not be copied every frame. Instead we shoul... | () -> ~[u8] {
return vec::from_fn(4962, |i| TEST_IMAGE[i]);
}
pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
// Can't remember why we do this. Maybe it's what cairo wants
static FORCE_DEPTH: uint = 4;
match stb_image::load_from_memory_with_depth(buffer, FORCE_DEPTH, true) {
stb_imag... | test_image_bin | identifier_name |
Api.ts | module Api {
export class | {
get = (a: boolean, b: number, c: string, d: number, e: number, f: any, g: number, h: number, i: number, j: number, k: number, l: number, m: number) : Promise<Date> => {
return new Promise<Date>((resolve) => resolve($.ajax({method: 'GET',url: '/api/testapi/get',data: {a, b, c, d, e, f, g, h, i... | NewTestApiService | identifier_name |
Api.ts | module Api {
export class NewTestApiService {
| }
post = (a: boolean, b: number, c: string, d: number, e: number, f: any, g: number, h: number, i: number, j: number, k: number, l: number, m: number) : Promise<any> => {
return new Promise<any>((resolve) => resolve($.ajax({method: 'POST',url: '/api/testapi/post',data: {a, b, c, d, e, f, g... | get = (a: boolean, b: number, c: string, d: number, e: number, f: any, g: number, h: number, i: number, j: number, k: number, l: number, m: number) : Promise<Date> => {
return new Promise<Date>((resolve) => resolve($.ajax({method: 'GET',url: '/api/testapi/get',data: {a, b, c, d, e, f, g, h, i, j, k... | random_line_split |
Settings.js | import React, { useCallback, useState } from 'react';
import { css } from 'emotion';
import { Button, Col, Input, Row } from 'reactstrap';
import Localized from 'components/Localized/Localized';
import LocationsCount from 'components/LocationsCount/LocationsCount';
import { useTranslation } from 'react-i18next';
import... |
export default React.memo(Settings); | random_line_split | |
preprocess_test.py | # Copyright 2021 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, ... | config_path = os.path.join(_SCRIPT_PATH, 'config.json')
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
cleaned_csv_path = os.path.join(tmp_dir, 'cleaned.csv')
utils.create_csv_mcf(csv_files, cleaned_csv_path, config,
... | def test_csv(self):
csv_files = []
test_config = {
'type': 'xls',
'path': 'testdata/2019.xls',
'args': {
'header': 3,
'skipfooter': 3
}
}
with tempfile.TemporaryDirectory() as tmp_dir:
xls_file_pa... | identifier_body |
preprocess_test.py | # Copyright 2021 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):
csv_files = []
test_config = {
'type': 'xls',
'path': 'testdata/2019.xls',
'args': {
'header': 3,
'skipfooter': 3
}
}
with tempfile.TemporaryDirectory() as tmp_dir:
xls_file_path = os.path... | test_csv | identifier_name |
preprocess_test.py | # Copyright 2021 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, ... | config_path = os.path.join(_SCRIPT_PATH, 'config.json')
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
cleaned_csv_path = os.path.join(tmp_dir, 'cleaned.csv')
utils.create_csv_mcf(csv_files, cleaned_csv_path, config,
... | read_file = preprocess._clean_dataframe(read_file)
read_file.insert(_YEAR_INDEX, 'Year', '2019')
read_file.to_csv(csv_file_path, index=None, header=True)
csv_files.append(csv_file_path)
| random_line_split |
api.service.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http';
import { ApiService } from './api.service'; | import { HttpTestingController } from '@angular/common/http/testing';
describe('Service: Api', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
ApiService,
]
});
});
it('should return a venue', () => {
const apiSer... | import { VenueItem } from './api.mock.service';
import { HttpClientTestingModule } from '@angular/common/http/testing'; | random_line_split |
types.rs | #[derive(Debug, Clone)]
pub enum FnType {
Simple,
None,
}
impl<'a> Into<String> for &'a FnType {
fn into(self) -> String {
match self {
&FnType::Simple => String::from("SIMPLE"),
_ => String::from(""),
}
}
}
impl Into<String> for FnType {
fn into(self) -> St... | (s: String) -> FnType {
match s.as_ref() {
"SIMPLE" => FnType::Simple,
_ => FnType::None,
}
}
}
impl PartialEq for FnType {
fn eq(&self, st: &FnType) -> bool {
let s: String = self.into();
let o: String = st.into();
s == o
}
}
#[derive(Debug,... | from | identifier_name |
types.rs | #[derive(Debug, Clone)]
pub enum FnType {
Simple,
None,
}
impl<'a> Into<String> for &'a FnType {
fn into(self) -> String {
match self { | }
impl Into<String> for FnType {
fn into(self) -> String {
(&self).into()
}
}
impl From<String> for FnType {
fn from(s: String) -> FnType {
match s.as_ref() {
"SIMPLE" => FnType::Simple,
_ => FnType::None,
}
}
}
impl PartialEq for FnType {
fn eq(&se... | &FnType::Simple => String::from("SIMPLE"),
_ => String::from(""),
}
} | random_line_split |
scraper.py | """
This module contains a single class that manages the scraping of data
from one or more supermarkets on mysupermarket.co.uk
"""
from datetime import datetime
from os import remove
from os.path import isfile, getmtime
from time import time
from scrapy import signals
from scrapy.crawler import Crawler
from scrapy.uti... | (self, supermarket):
"""Check whether a JSON file already exists for data scraped from
the given supermarket, and if so, whether it was created today.
Note that 'created today' is not the same as 'age < 24 hours'. Prices
are assumed to change overnight so a cachefile created at 9pm
... | cache_exists | identifier_name |
scraper.py | """
This module contains a single class that manages the scraping of data
from one or more supermarkets on mysupermarket.co.uk
"""
from datetime import datetime
from os import remove
from os.path import isfile, getmtime
from time import time
from scrapy import signals
from scrapy.crawler import Crawler
from scrapy.uti... |
def cache_exists(self, supermarket):
"""Check whether a JSON file already exists for data scraped from
the given supermarket, and if so, whether it was created today.
Note that 'created today' is not the same as 'age < 24 hours'. Prices
are assumed to change overnight so a cachefil... | """Create a CachingScraper for the given supermarket(s).
Keyword arguments:
supermarkets -- a list of supermarkets to scrape
force_refresh -- if True, cachefiles will not be used
"""
self.force_refresh = force_refresh
self.supermarkets = supermarkets
self... | identifier_body |
scraper.py | """
This module contains a single class that manages the scraping of data
from one or more supermarkets on mysupermarket.co.uk
"""
from datetime import datetime
from os import remove
from os.path import isfile, getmtime
from time import time
from scrapy import signals
from scrapy.crawler import Crawler
from scrapy.uti... | yesterday is considered out of date at 9am today (but a cachefile
created at 9am is not out of date at 9pm).
Keyword arguments:
supermarket -- the supermarket whose cachefile should be checked
"""
cachefile = supermarket_filename(supermarket)
if not isfile(cachef... | random_line_split | |
scraper.py | """
This module contains a single class that manages the scraping of data
from one or more supermarkets on mysupermarket.co.uk
"""
from datetime import datetime
from os import remove
from os.path import isfile, getmtime
from time import time
from scrapy import signals
from scrapy.crawler import Crawler
from scrapy.uti... |
reactor_control.start_crawling()
| self.setup_crawler(supermarket, reactor_control) | conditional_block |
build_lipid.py | # Author: Samuel Genheden, samuel.genheden@gmail.com
"""
Program to build lipids from a template, similarly to MARTINI INSANE
Is VERY experimental!
"""
import argparse
import os
import xml.etree.ElementTree as ET
import numpy as np
from sgenlib import pdb
class BeadDefinition(object):
def __init__(self):
... | class LipidCollection(object):
def __init__(self):
self.lipids = {}
def load(self, filename):
tree = ET.parse(filename)
# Parse lipids
for child in tree.getroot():
if child.tag != "lipid":
continue
lipid = LipidTemplate()
li... | random_line_split | |
build_lipid.py | # Author: Samuel Genheden, samuel.genheden@gmail.com
"""
Program to build lipids from a template, similarly to MARTINI INSANE
Is VERY experimental!
"""
import argparse
import os
import xml.etree.ElementTree as ET
import numpy as np
from sgenlib import pdb
class BeadDefinition(object):
def __init__(self):
... | self.tail.append(b)
def __str__(self):
return self.name+"\n\t"+"\n\t".join(b.__str__() for b in self.beads)
class LipidCollection(object):
def __init__(self):
self.lipids = {}
def load(self, filename):
tree = ET.parse(filename)
# Parse lipids
... | if "name" in element.attrib:
self.name = element.attrib["name"]
else:
return
if "head" in element.attrib:
self.headname = element.attrib["head"].split()
if "tail" in element.attrib:
self.tailname = element.attrib["tail"].split()
for child... | identifier_body |
build_lipid.py | # Author: Samuel Genheden, samuel.genheden@gmail.com
"""
Program to build lipids from a template, similarly to MARTINI INSANE
Is VERY experimental!
"""
import argparse
import os
import xml.etree.ElementTree as ET
import numpy as np
from sgenlib import pdb
class BeadDefinition(object):
def __init__(self):
... |
b = BeadDefinition()
b.parse(child)
if b.name is not None:
self.beads.append(b)
if b.name in self.headname :
self.head.append(b)
elif b.name in self.tailname :
self.tail.append(b)
def __str_... | continue | conditional_block |
build_lipid.py | # Author: Samuel Genheden, samuel.genheden@gmail.com
"""
Program to build lipids from a template, similarly to MARTINI INSANE
Is VERY experimental!
"""
import argparse
import os
import xml.etree.ElementTree as ET
import numpy as np
from sgenlib import pdb
class BeadDefinition(object):
def __init__(self):
... | (self, filename):
tree = ET.parse(filename)
# Parse lipids
for child in tree.getroot():
if child.tag != "lipid":
continue
lipid = LipidTemplate()
lipid.parse(child)
if lipid.name is not None:
self.lipids[lipid.name... | load | identifier_name |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later versio... |
#[test]
fn get_master_password() {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
... | {
let actual = master_key("test", "pass", &SiteVariant::Password)
.unwrap()
.to_vec();
assert_eq!(actual,
vec![51, 253, 82, 252, 68, 97, 191, 162, 127, 73, 153, 160, 52, 128, 204, 4, 183,
190, 106, 180, 68, 126, 100, 94, 132, 141, 99, 1... | identifier_body |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later versio... | () {
let master_key = master_key("test", "pass", &SiteVariant::Password).unwrap();
let actual = password_for_site(&master_key,
"site",
&SiteType::Maximum,
&(1 as i32),
... | get_master_password | identifier_name |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later versio... | use common;
use common::{SiteVariant, SiteType};
pub fn master_key(full_name: &str,
master_password: &str,
site_variant: &SiteVariant)
-> Option<[u8; common::KEY_LENGTH]> {
let scope = common::scope_for_variant(site_variant);
if scope.is_some() {
l... | * You should have received a copy of the GNU General Public License
* along with Master Password. If not, see <http://www.gnu.org/licenses/>.
*/
use self::ring::{digest, hmac}; | random_line_split |
mpw_v3.rs | extern crate ring;
/*
* This file is part of Master Password.
*
* Master Password is free software: you can redistribute it and/or modify
* Mit under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later versio... | else {
Some(String::from_utf8(password.iter().map(|c| c.unwrap()).collect::<Vec<u8>>())
.unwrap())
}
} else {
None
}
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{SiteType, SiteVariant};
#[... | {
None
} | conditional_block |
move_source_file.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Moves a C++ file to a new location, updating any include paths that
point to it, and re-ordering headers as needed. Updates inc... |
if __name__ == '__main__':
# Need to add the directory containing sort-headers.py to the Python
# classpath.
sys.path.append(os.path.abspath(os.path.join(sys.path[0], '..')))
sort_headers = __import__('sort-headers')
HANDLED_EXTENSIONS = ['.cc', '.mm', '.h', '.hh']
def MakeDestinationPath(from_path, to_path)... | random_line_split | |
move_source_file.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Moves a C++ file to a new location, updating any include paths that
point to it, and re-ordering headers as needed. Updates inc... | (from_path, to_path):
"""Given a file that has moved from |from_path| to |to_path|,
updates the moved file's include guard to match the new path and
updates all references to the file in other source files. Also tries
to update references in .gyp(i) files using a heuristic.
"""
# Include paths always use fo... | UpdatePostMove | identifier_name |
move_source_file.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Moves a C++ file to a new location, updating any include paths that
point to it, and re-ordering headers as needed. Updates inc... | UpdatePostMove(from_path, to_path)
return 0
if __name__ == '__main__':
sys.exit(main())
| if not os.path.isdir('.git'):
print 'Fatal: You must run from the root of a git checkout.'
return 1
args = sys.argv[1:]
if not len(args) in [2, 3]:
print ('Usage: move_source_file.py [--already-moved] FROM_PATH TO_PATH'
'\n\n%s' % __doc__)
return 1
already_moved = False
if args[0] ==... | identifier_body |
move_source_file.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Moves a C++ file to a new location, updating any include paths that
point to it, and re-ordering headers as needed. Updates inc... |
mffr.MultiFileFindReplace(
r'([\'"])%s([\'"])' % re.escape(PathMinusFirstComponent(from_path)),
r'\1%s\2' % PathMinusFirstComponent(to_path),
['*.gyp*'])
def MakeIncludeGuardName(path_from_root):
"""Returns an include guard name given a path from root."""
guard = path_from_root.replace('/', '... | return parts[0] | conditional_block |
packet2snort.py | <pcap> input pcap file"
print "-p <packetnr> input packet number in pcap"
print "-s to output snort rule from single packet"
sys.exit(0)
#converts layer 3 and 4 protocols into rules:
# IP, TCP, UDP & ICMP
def basicconvert(singlepacket, packetnr0):
try:
print ("\n{1}----- Snort Rules For Packet Number {0}-----{2... |
else:
print ("alert udp $HOME_NET any -> any 53 (msg: \"Suspicious DNS request for {0} detected!\"; content:\"|01 00 00 01 00 00 00 00 00 00|\"; depth:10; offset:2; content:\"".format(hostname)),
dnsplit = hostname.split('.')
for word in dnsplit:
if word != '':
numbers = len(word)... | hostaddr = singlepacket[DNSRR].rdata
print ("alert udp any 53 -> $HOME_NET any (msg: \"Suspicious DNS reply for {0} with address {1} detected!\"; content:\"|00 01 00 01|\"; content:\"|00 04".format(hostname, hostaddr)),
addrsplit = hostaddr.split('.')
for addr in addrsplit:
hexaddr = format(in... | conditional_block |
packet2snort.py | <pcap> input pcap file"
print "-p <packetnr> input packet number in pcap"
print "-s to output snort rule from single packet"
sys.exit(0)
#converts layer 3 and 4 protocols into rules:
# IP, TCP, UDP & ICMP
def | (singlepacket, packetnr0):
try:
print ("\n{1}----- Snort Rules For Packet Number {0}-----{2}".format(packetnr0, G, W))
# Print IP Layer Rules
# Check if the IP layer is present in the packet
if IP in singlepacket:
print ("{0}----- Layer 3/4 Rules -------{1}".format(G, W))
ipsource = singlepacket[IP].src
i... | basicconvert | identifier_name |
packet2snort.py | {0}----- Layer 3/4 Rules -------{1}".format(G, W))
ipsource = singlepacket[IP].src
ipdest = singlepacket[IP].dst
# Print TCP Layer Rules
# Check if TCP is present in the packet
if TCP in singlepacket:
print ("{0}----- TCP ---\n{1}".format(G, W))
tcpsourceport = singlepacket[TCP].sport
tcpdestport =... | sys.exit(1)
| random_line_split | |
packet2snort.py | <pcap> input pcap file"
print "-p <packetnr> input packet number in pcap"
print "-s to output snort rule from single packet"
sys.exit(0)
#converts layer 3 and 4 protocols into rules:
# IP, TCP, UDP & ICMP
def basicconvert(singlepacket, packetnr0):
| if DNSRR in singlepacket:
hostaddr = singlepacket[DNSRR].rdata
print ("alert udp any 53 -> $HOME_NET any (msg: \"Suspicious DNS reply for {0} with address {1} detected!\"; content:\"|00 01 00 01|\"; content:\"|00 04".format(hostname, hostaddr)),
addrsplit = hostaddr.split('.')
for addr in ... | try:
print ("\n{1}----- Snort Rules For Packet Number {0}-----{2}".format(packetnr0, G, W))
# Print IP Layer Rules
# Check if the IP layer is present in the packet
if IP in singlepacket:
print ("{0}----- Layer 3/4 Rules -------{1}".format(G, W))
ipsource = singlepacket[IP].src
ipdest = singlepacket[IP].dst... | identifier_body |
commands.py | import re, shlex
import hangups
from hangupsbot.utils import text_to_segments
from hangupsbot.handlers import handler, StopEventHandling
from hangupsbot.commands import command
default_bot_alias = '/bot'
def find_bot_alias(aliases_list, text):
"""Return True if text starts with bot alias"""
command = text... | (text):
"""check whether the bot alias is too long or not"""
if default_bot_alias in text:
return True
else:
return False
@handler.register(priority=5, event=hangups.ChatMessageEvent)
def handle_command(bot, event):
"""Handle command messages"""
# Test if message is not empty
i... | is_bot_alias_too_long | identifier_name |
commands.py | import re, shlex
import hangups
from hangupsbot.utils import text_to_segments
from hangupsbot.handlers import handler, StopEventHandling
from hangupsbot.commands import command
default_bot_alias = '/bot'
def find_bot_alias(aliases_list, text):
"""Return True if text starts with bot alias"""
command = text... |
@handler.register(priority=5, event=hangups.ChatMessageEvent)
def handle_command(bot, event):
"""Handle command messages"""
# Test if message is not empty
if not event.text:
return
# Get list of bot aliases
aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases')
if... | """check whether the bot alias is too long or not"""
if default_bot_alias in text:
return True
else:
return False | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.