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
stored_values.py
#!/usr/bin/env python ''' @author Luke C @date Mon Mar 25 09:57:59 EDT 2013 @file ion/util/stored_values.py ''' from pyon.core.exception import NotFound import gevent class StoredValueManager(object): def __init__(self, container): self.store = container.object_store def stored_value_cas(self, doc_...
self.store.delete_doc(doc_key)
identifier_body
stored_values.py
#!/usr/bin/env python ''' @author Luke C @date Mon Mar 25 09:57:59 EDT 2013 @file ion/util/stored_values.py ''' from pyon.core.exception import NotFound import gevent class StoredValueManager(object): def __init__(self, container): self.store = container.object_store def stored_value_cas(self, doc_...
doc_id, rev = self.store.update_doc(doc) return doc_id, rev def read_value(self, doc_key): doc = self.store.read_doc(doc_key) return doc def read_value_mult(self, doc_keys, strict=False): doc_list = self.store.read_doc_mult(doc_keys, strict=strict) return doc_l...
doc[k] = v
conditional_block
aarch64_linux_android.rs
use crate::spec::{SanitizerSet, Target, TargetOptions}; // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a // for target ABI requirements. pub fn target() -> Target { Target { llvm_target: "aarch64-linux-android".to_string(), pointer_width: 64,
// As documented in https://developer.android.com/ndk/guides/cpu-features.html // the neon (ASIMD) and FP must exist on all android aarch64 targets. features: "+neon,+fp-armv8".to_string(), supported_sanitizers: SanitizerSet::CFI | SanitizerSet::HWADDRESS, ..s...
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), options: TargetOptions { max_atomic_width: Some(128),
random_line_split
aarch64_linux_android.rs
use crate::spec::{SanitizerSet, Target, TargetOptions}; // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a // for target ABI requirements. pub fn target() -> Target
{ Target { llvm_target: "aarch64-linux-android".to_string(), pointer_width: 64, data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), options: TargetOptions { max_atomic_width: Some(128), // As doc...
identifier_body
aarch64_linux_android.rs
use crate::spec::{SanitizerSet, Target, TargetOptions}; // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a // for target ABI requirements. pub fn
() -> Target { Target { llvm_target: "aarch64-linux-android".to_string(), pointer_width: 64, data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(), arch: "aarch64".to_string(), options: TargetOptions { max_atomic_width: Some(128), ...
target
identifier_name
count_is_at_least.rs
use malachite_base::iterators::count_is_at_least; use std::iter::repeat;
assert_eq!(count_is_at_least(xs.iter(), n), result); assert_eq!(count_is_at_least(xs.iter().rev(), n), result); } #[test] fn test_count_is_at_least() { count_is_at_least_helper(&[], 0, true); count_is_at_least_helper(&[], 1, false); count_is_at_least_helper(&[5], 0, true); count_is_at_least_hel...
fn count_is_at_least_helper(xs: &[u8], n: usize, result: bool) {
random_line_split
count_is_at_least.rs
use malachite_base::iterators::count_is_at_least; use std::iter::repeat; fn count_is_at_least_helper(xs: &[u8], n: usize, result: bool) { assert_eq!(count_is_at_least(xs.iter(), n), result); assert_eq!(count_is_at_least(xs.iter().rev(), n), result); } #[test] fn test_count_is_at_least()
{ count_is_at_least_helper(&[], 0, true); count_is_at_least_helper(&[], 1, false); count_is_at_least_helper(&[5], 0, true); count_is_at_least_helper(&[5], 1, true); count_is_at_least_helper(&[5], 2, false); count_is_at_least_helper(&[1, 2, 3, 4], 4, true); count_is_at_least_helper(&[1, 2, 3,...
identifier_body
count_is_at_least.rs
use malachite_base::iterators::count_is_at_least; use std::iter::repeat; fn
(xs: &[u8], n: usize, result: bool) { assert_eq!(count_is_at_least(xs.iter(), n), result); assert_eq!(count_is_at_least(xs.iter().rev(), n), result); } #[test] fn test_count_is_at_least() { count_is_at_least_helper(&[], 0, true); count_is_at_least_helper(&[], 1, false); count_is_at_least_helper(&[5...
count_is_at_least_helper
identifier_name
HandleCreate.ts
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; withou...
notifyOnSuccess(); return result; }).catch((error) => { notifyOnError(error); throw error; }); };
{ return enterpriseGroupSyncPlugin.actions.onDirectoryServiceBackendUpdate(false, formValues, result.backend.id, serviceType).then(notifyOnSuccess); }
conditional_block
HandleCreate.ts
/*
* it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Publ...
* Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify
random_line_split
helper.py
td: td() cherrypy.engine.exit() servers_copy = list(six.iteritems(getattr(cherrypy, 'servers', {}))) for name, server in servers_copy: server.unsubscribe() del cherrypy.servers[name] class NativeServerSupervisor(LocalSupervisor): """Server supervisor...
(**options): cherrypy.server.wsgi_version = ('u', 0) return LocalWSGISupervisor(**options) class CPWebCase(webtest.WebCase): script_name = '' scheme = 'http' available_servers = {'wsgi': LocalWSGISupervisor, 'wsgi_u': get_wsgi_u_supervisor, 'nati...
get_wsgi_u_supervisor
identifier_name
helper.py
sgi_supervisor, 'modfcgid': get_modfcgid_supervisor, 'modfastcgi': get_modfastcgi_supervisor, } default_server = 'wsgi' @classmethod def _setup_server(cls, supervisor, conf): v = sys.version.split()[0] log.info('Pyth...
'extra': extra,
random_line_split
helper.py
, 'setup_server'): # Clear the cherrypy tree and clear the wsgi server so that # it can be updated with the new root cherrypy.tree = cherrypy._cptree.Tree() cherrypy.server.httpserver = None cls.setup_server() # Add a resource for verifying there a...
try: try: # Mac, UNIX os.wait() except AttributeError: # Windows try: pid = self.get_pid() except IOError: # Assume the subprocess deleted the pidfile on shutdown. ...
identifier_body
helper.py
.socket_port': supervisor.port, 'server.protocol_version': supervisor.protocol, 'environment': 'test_suite', }) if supervisor.scheme == 'https': # baseconf['server.ssl_module'] = 'builtin' baseconf['server.ssl_cer...
args.append('-i') args.append(i)
conditional_block
main.rs
#![recursion_limit = "128"] #![allow(dead_code)] #[macro_use] mod util; mod dispatch; use anyhow::Result; use monger_core::os::OS_NAMES; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about, author)] enum Options { /// clear the database files for an installed MongoDB version Clear { ...
#[structopt(name = "MONGODB_ARGS", last(true))] mongod_args: Vec<String>, }, } #[derive(Debug, StructOpt)] enum Defaults { /// clears the previously set default arguments Clear, /// prints the default arguments used when starting a mongod Get, /// sets the default arguments us...
id: String, /// extra arguments for the mongod being run
random_line_split
main.rs
#![recursion_limit = "128"] #![allow(dead_code)] #[macro_use] mod util; mod dispatch; use anyhow::Result; use monger_core::os::OS_NAMES; use structopt::StructOpt; #[derive(Debug, StructOpt)] #[structopt(about, author)] enum
{ /// clear the database files for an installed MongoDB version Clear { /// the ID of the MongoDB version whose files should be cleared #[structopt(name = "ID")] id: String, }, /// deletes an installed MongoDB version Delete { /// the ID of the MongoDB version to de...
Options
identifier_name
roman_numerals3.py
# https://www.codewars.com/kata/roman-numerals-encoder/train/python def solution(n): # Print the arguments print('n = {}'.format(n)) roman_blueprint = [] # List of lists to store format structure: [[<letter>, <count>], ...] result = [] # Store the final roman numeral result # Calculate for roman numerals # C...
if (400 <= numD <= 899): numD = 1 else: numD = 0 roman_blueprint.append(['D', numD]) # Calculate the M's -- 1000 numM = n % 5000 # Do modulo 10, since we want to look at the M's if (numM <= 899): numM = 0 elif (900 <= numM <= 1899): # (0 * 1000) + 0 <= (numM - 900) <= (0 * 1000) + 999 numM = 1 elif...
numC = -2 roman_blueprint.append(['C', numC]) # Calculate the D's -- 500 numD = n % 1000 # Do modulo 1000, since we want to look at the D's
random_line_split
roman_numerals3.py
# https://www.codewars.com/kata/roman-numerals-encoder/train/python def solution(n): # Print the arguments print('n = {}'.format(n)) roman_blueprint = [] # List of lists to store format structure: [[<letter>, <count>], ...] result = [] # Store the final roman numeral result # Calculate for roman numerals # C...
elif (90 <= numC <= 189): # (0 * 100) + 0 <= (numC - 90) <= (0 * 100) + 99 numC = 1 elif (190 <= numC <= 289): # (1 * 100) + 0 <= (numC - 90) <= (1 * 100) + 99 numC = 2 elif (290 <= numC <= 389): # (2 * 100) + 0 <= (numC - 90) <= (2 * 100) + 99 numC = 3 elif (390 <= numC <= 399): # (3 * 100) + 0 <= (numC - 9...
numC = 0
conditional_block
roman_numerals3.py
# https://www.codewars.com/kata/roman-numerals-encoder/train/python def
(n): # Print the arguments print('n = {}'.format(n)) roman_blueprint = [] # List of lists to store format structure: [[<letter>, <count>], ...] result = [] # Store the final roman numeral result # Calculate for roman numerals # Calculate the I's -- 1 numI = n % 5 # Do modulo 5, since we want to look at t...
solution
identifier_name
roman_numerals3.py
# https://www.codewars.com/kata/roman-numerals-encoder/train/python def solution(n): # Print the arguments
# Calculate the X's -- 10 numX = n % 50 # Do modulo 10, since we want to look at the X's if (numX <= 8): numX = 0 elif (9 <= numX <= 18): # (0 * 10) + 0 <= (numX - 9) <= (0 * 10) + 9 numX = 1 elif (19 <= numX <= 28): # (1 * 10) + 0 <= (numX - 9) <= (1 * 10) + 9 numX = 2 elif (29 <= numX <= 38): # (2 * ...
print('n = {}'.format(n)) roman_blueprint = [] # List of lists to store format structure: [[<letter>, <count>], ...] result = [] # Store the final roman numeral result # Calculate for roman numerals # Calculate the I's -- 1 numI = n % 5 # Do modulo 5, since we want to look at the I's if (numI == 4): # If...
identifier_body
grove_slide_potentiometer.py
#!/usr/bin/env python # # GrovePi Example for using the Grove Slide Potentiometer (http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this exa...
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the ...
random_line_split
grove_slide_potentiometer.py
#!/usr/bin/env python # # GrovePi Example for using the Grove Slide Potentiometer (http://www.seeedstudio.com/wiki/Grove_-_Slide_Potentiometer) # # The GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this exa...
print("sensor_value =", sensor_value) except IOError: print ("Error")
grovepi.digitalWrite(led,0)
conditional_block
main.rs
// tt - time tracker // // Usage: tt (stop the current task) // tt <task name or description> start or resume a task // // Time tracking state is read from, and appended to ./tt.txt // There is no reporting functionality yet. // // Released under the GPL v3 licence. extern crate chrono; extern crate regex; exte...
// but regain exclusive ownership after the scope is exited // see: https://stackoverflow.com/questions/33831265/how-to-use-a-file-for-reading-and-writing { let reader = BufReader::new(&mut file); // "reader" is borrowing *the* mutable reference to file, for "reader"'s lifetime for wrapped_...
{ let filename = "tt.txt"; // open a tt.txt file in the local directory let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(filename) .unwrap(); // now read the whole file to get the latest state ...
identifier_body
main.rs
// tt - time tracker // // Usage: tt (stop the current task) // tt <task name or description> start or resume a task // // Time tracking state is read from, and appended to ./tt.txt // There is no reporting functionality yet. // // Released under the GPL v3 licence. extern crate chrono; extern crate regex; exte...
} } file.seek(End(0)); let now = Local::now(); if latest_date == None || latest_date.unwrap().year() != now.year() || latest_date.unwrap().month() != now.month() || latest_date.unwrap().day() != now.day() { // if today isn't the same date as the latest date fou...
{ let captures = time_activity_re.captures(&line).unwrap(); let hour = captures.at(1).unwrap().parse::<u32>().unwrap(); let minute = captures.at(2).unwrap().parse::<u32>().unwrap(); let activity = captures.at(3).unwrap(); latest_datetime =...
conditional_block
main.rs
// tt - time tracker // // Usage: tt (stop the current task) // tt <task name or description> start or resume a task // // Time tracking state is read from, and appended to ./tt.txt // There is no reporting functionality yet. // // Released under the GPL v3 licence. extern crate chrono; extern crate regex; exte...
() { let filename = "tt.txt"; // open a tt.txt file in the local directory let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .open(filename) .unwrap(); // now read the whole file to get the latest state...
main
identifier_name
main.rs
// tt - time tracker // // Usage: tt (stop the current task) // tt <task name or description> start or resume a task // // Time tracking state is read from, and appended to ./tt.txt // There is no reporting functionality yet. // // Released under the GPL v3 licence. extern crate chrono; extern crate regex; exte...
// if there was no latest activity *and* there is no activity, then there's no point in writing a second blank line with just a time if latest_activity == None { return; } file.write_all(format!("{}\n", now.format("%H:%M")).as_bytes()); } // "file" is automatically ...
let activity = env::args().skip(1).join(" "); // use all arguments (apart from the program name) as a description of an activity if (activity.len() > 0) { file.write_all(format!("{} {}\n", now.format("%H:%M"), activity).as_bytes()); } else {
random_line_split
printer.py
_ep=0x01, *args, **kwargs): # noqa: N803 """ :param idVendor: Vendor ID :param idProduct: Product ID :param usb_args: Optional USB arguments (e.g. custom_match) :param timeout: Is the time limit of the USB operation. Default without timeout. :param in_ep...
(self, devfile="/dev/usb/lp0", auto_flush=True, *args, **kwargs): """ :param devfile: Device file under dev filesystem :param auto_flush: automatically call flush after every call of _raw() """ Escpos.__init__(self, *args, **kwargs) self.devfile = devfile self.au...
__init__
identifier_name
printer.py
_ep=0x01, *args, **kwargs): # noqa: N803 """ :param idVendor: Vendor ID :param idProduct: Product ID :param usb_args: Optional USB arguments (e.g. custom_match) :param timeout: Is the time limit of the USB operation. Default without timeout. :param in_ep...
def _raw(self, msg): """ Print any command sent in raw format :param msg: arbitrary code to be printed :type msg: bytes """ self.device.sendall(msg) def _read(self): """ Read data from the TCP socket """ return self.device.recv(16) def close(self...
print("Could not open socket for {0}".format(self.host))
conditional_block
printer.py
_ep=0x01, *args, **kwargs): # noqa: N803 """ :param idVendor: Vendor ID :param idProduct: Product ID :param usb_args: Optional USB arguments (e.g. custom_match) :param timeout: Is the time limit of the USB operation. Default without timeout. :param in_ep...
.. inheritance-diagram:: escpos.printer.Network :parts: 1 """ def __init__(self, host, port=9100, timeout=60, *args, **kwargs): """ :param host: Printer's hostname or IP address :param port: Port to write to :param timeout: timeout in seconds for the socket-...
Otherwise the normal usecase would be to have a printer with ethernet interface. This type of printer should work the same with this class. For the address of the printer check its manuals. inheritance:
random_line_split
printer.py
:param timeout: Is the time limit of the USB operation. Default without timeout. :param in_ep: Input end point :param out_ep: Output end point """ Escpos.__init__(self, *args, **kwargs) self.timeout = timeout self.in_ep = in_ep self.out_ep = out_ep usb_a...
""" Print any command sent in raw format :param msg: arbitrary code to be printed :type msg: bytes """ self._output_list.append(msg)
identifier_body
index_worker.py
# -*- coding: utf-8 -*- import os import sys import fcntl import signal import logging import logging.config from ConfigParser import ConfigParser from openprocurement.search.version import __version__ from openprocurement.search.engine import IndexEngine, logger from openprocurement.search.utils import decode_bool_...
if config.get('lot_api_url', None): source = DgfLotSource(config, True) DgfLotIndex(engine, source, config) engine.run() except Exception as e: logger.exception("Unhandled Exception: %s", str(e)) finally: lock_file.close() os.remove(lock_filename)...
source = AssetSource(config, True) AssetIndex(engine, source, config)
conditional_block
index_worker.py
# -*- coding: utf-8 -*- import os import sys import fcntl import signal import logging import logging.config from ConfigParser import ConfigParser from openprocurement.search.version import __version__ from openprocurement.search.engine import IndexEngine, logger from openprocurement.search.utils import decode_bool_...
(signo, frame): logger.info("Signal received %d", signo) if engine and hasattr(engine, 'stop_childs'): engine.should_exit = True engine.stop_childs() signal.alarm(3) # sys.exit(0) def main(): if len(sys.argv) < 2: print("Usage: index_worker etc/search.ini [custom_index_name...
sigterm_handler
identifier_name
index_worker.py
# -*- coding: utf-8 -*- import os import sys import fcntl import signal import logging import logging.config from ConfigParser import ConfigParser from openprocurement.search.version import __version__ from openprocurement.search.engine import IndexEngine, logger from openprocurement.search.utils import decode_bool_...
lock_filename) lock_file.close() return 1 signal.signal(signal.SIGTERM, sigterm_handler) # signal.signal(signal.SIGINT, sigterm_handler) try: global engine engine = IndexEngine(config) if config.get('orgs_db', None): source = OrgsSource(confi...
fcntl.lockf(lock_file, fcntl.LOCK_EX + fcntl.LOCK_NB) lock_file.write(str(os.getpid()) + "\n") lock_file.flush() except: logger.error("Can't get lock %s maybe already started",
random_line_split
index_worker.py
# -*- coding: utf-8 -*- import os import sys import fcntl import signal import logging import logging.config from ConfigParser import ConfigParser from openprocurement.search.version import __version__ from openprocurement.search.engine import IndexEngine, logger from openprocurement.search.utils import decode_bool_...
def main(): if len(sys.argv) < 2: print("Usage: index_worker etc/search.ini [custom_index_names_file]") sys.exit(1) if '--version' in sys.argv: print(__version__) sys.exit(0) parser = ConfigParser() parser.read(sys.argv[1]) config = dict(parser.items('search_engi...
logger.info("Signal received %d", signo) if engine and hasattr(engine, 'stop_childs'): engine.should_exit = True engine.stop_childs() signal.alarm(3) # sys.exit(0)
identifier_body
resource.ts
/* Copyright (C) 2013-2020 by Justin DuJardin and Contributors Licensed under the Apache License, Version 2.0 (the "License");
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions...
you may not use this file except in compliance with the License. You may obtain a copy of the License at
random_line_split
resource.ts
/* Copyright (C) 2013-2020 by Justin DuJardin and Contributors 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...
implements IResource { extension: string; constructor(public url: string = null, public data: any = null) {} load(data?: any): Promise<Resource> { return Promise.reject(errors.CLASS_NOT_IMPLEMENTED); } fetch(url?: string): Promise<Resource> { return Promise.reject(errors.CLASS_NOT_IMPLEMENTED); ...
Resource
identifier_name
resource.ts
/* Copyright (C) 2013-2020 by Justin DuJardin and Contributors 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...
fetch(url?: string): Promise<Resource> { return Promise.reject(errors.CLASS_NOT_IMPLEMENTED); } }
{ return Promise.reject(errors.CLASS_NOT_IMPLEMENTED); }
identifier_body
tag-align-shape.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)}; let y = format!("{:?}", x); println!("y = {:?}", y); assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string()); }
identifier_body
tag-align-shape.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// option. This file may not be copied, modified, or distributed // except according to those terms. #[derive(Debug)] enum a_tag { a_tag_var(u64) } #[derive(Debug)] struct t_rec { c8: u8, t: a_tag } pub fn main() { let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)}; let y = format!("{:?}", x); ...
random_line_split
tag-align-shape.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ a_tag_var(u64) } #[derive(Debug)] struct t_rec { c8: u8, t: a_tag } pub fn main() { let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)}; let y = format!("{:?}", x); println!("y = {:?}", y); assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string()); }
a_tag
identifier_name
nats-connector.ts
import * as nats from 'nats'; import * as _ from 'lodash'; import { logger } from '@cdm-logger/server'; import { CdmLogger } from '@cdm-logger/core'; type ILogger = CdmLogger.ILogger; export class NatsConnector { private opts: nats.ClientOpts; private client: nats.Client; private logger: ILogger; pr...
}); client.on('error', e => { this.logger.error('NATS error.', e.message); this.logger.debug(e); reject(e); }); client.on('close', () => { this.logger.fatal('NATS connection close.'); }); ...
{ this.logger.warn('NATS client is disconnected.'); this.connected = false; }
conditional_block
nats-connector.ts
import * as nats from 'nats'; import * as _ from 'lodash'; import { logger } from '@cdm-logger/server'; import { CdmLogger } from '@cdm-logger/core'; type ILogger = CdmLogger.ILogger; export class NatsConnector { private opts: nats.ClientOpts; private client: nats.Client; private logger: ILogger; pr...
client.on('error', e => { this.logger.error('NATS error.', e.message); this.logger.debug(e); reject(e); }); client.on('close', () => { this.logger.fatal('NATS connection close.'); }); }); } ...
} });
random_line_split
nats-connector.ts
import * as nats from 'nats'; import * as _ from 'lodash'; import { logger } from '@cdm-logger/server'; import { CdmLogger } from '@cdm-logger/core'; type ILogger = CdmLogger.ILogger; export class
{ private opts: nats.ClientOpts; private client: nats.Client; private logger: ILogger; private connected: boolean; constructor(opts: nats.ClientOpts) { this.opts = _.defaultsDeep(opts, {}); this.logger = logger.child({ className: 'NatsConnector' }); } /** * Connect t...
NatsConnector
identifier_name
item.py
# Copyright 2009 Kieran Elliott <kierse@mediarover.tv> # # Media Rover is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Media Rover...
if self._url is None: raise InvalidRemoteData("report does not have a url") self._download = self.build_download()
raise InvalidRemoteData("report does not have a title")
conditional_block
item.py
# Copyright 2009 Kieran Elliott <kierse@mediarover.tv> # # Media Rover is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Media Rover...
(self): return NZBMATRIX # property definitions- - - - - - - - - - - - - - - - - - - - - - - - - - - delay = property(fget=_delay_property, fset=_delay_property, doc="schedule delay") # private methods- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def __init__(self, item, type, priority, quality...
source
identifier_name
item.py
# Copyright 2009 Kieran Elliott <kierse@mediarover.tv> # # Media Rover is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Media Rover...
if enclosure[0].getAttribute("url") is not "": self._url = enclosure[0].getAttribute("url") else: self._url = url if enclosure[0].getAttribute("length").isnumeric(): self._size = int(enclosure[0].getAttribute("length")) / 1024 / 1024 else: self._size = size else: self._size =...
self._title = titles[0].childNodes[0].data enclosure = self._item.getElementsByTagName("enclosure") if enclosure:
random_line_split
item.py
# Copyright 2009 Kieran Elliott <kierse@mediarover.tv> # # Media Rover is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Media Rover...
# property definitions- - - - - - - - - - - - - - - - - - - - - - - - - - - delay = property(fget=_delay_property, fset=_delay_property, doc="schedule delay") # private methods- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def __init__(self, item, type, priority, quality, delay, size=0, title=Non...
return NZBMATRIX
identifier_body
db.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sqlite3 from functools import partialmethod from asian_word_analyzer.login import connection_string from asian_word_analyzer.tools import detect_language class DbUtil: def __init__(self):
def compute_meanings(self, word): """ Find the possible meanings based on the input string by the user""" query = "SELECT meaning from Korean WHERE word='{}'".format(word) self.cursor.execute(query) meanings = self.cursor.fetchall() return [meaning[0] for meaning in...
if not os.path.isfile(connection_string): raise FileNotFoundError('Missing Korean database: {}'.format(connection_string)) self.connection = sqlite3.connect(connection_string) self.cursor = self.connection.cursor()
identifier_body
db.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os
from functools import partialmethod from asian_word_analyzer.login import connection_string from asian_word_analyzer.tools import detect_language class DbUtil: def __init__(self): if not os.path.isfile(connection_string): raise FileNotFoundError('Missing Korean database: {}'.format(connection...
import sqlite3
random_line_split
db.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sqlite3 from functools import partialmethod from asian_word_analyzer.login import connection_string from asian_word_analyzer.tools import detect_language class DbUtil: def __init__(self): if not os.path.isfile(connection_string):
self.connection = sqlite3.connect(connection_string) self.cursor = self.connection.cursor() def compute_meanings(self, word): """ Find the possible meanings based on the input string by the user""" query = "SELECT meaning from Korean WHERE word='{}'".format(word) se...
raise FileNotFoundError('Missing Korean database: {}'.format(connection_string))
conditional_block
db.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import sqlite3 from functools import partialmethod from asian_word_analyzer.login import connection_string from asian_word_analyzer.tools import detect_language class
: def __init__(self): if not os.path.isfile(connection_string): raise FileNotFoundError('Missing Korean database: {}'.format(connection_string)) self.connection = sqlite3.connect(connection_string) self.cursor = self.connection.cursor() def compute_meanings(self, wor...
DbUtil
identifier_name
memorize.rs
use std::collections::HashMap; use std::cmp::Eq; use std::hash::Hash; use std::cell::RefCell; use std::rc::Rc; pub struct Memorizer<I, O> { store: RefCell<HashMap<I, Rc<O>>>, func: Box<Fn(&Memorizer<I, O>, &I) -> O>, } impl<I: Clone + Hash + Eq, O> Memorizer<I, O> { pub fn
(f: Box<Fn(&Self, &I) -> O>) -> Memorizer<I, O> { Memorizer { store: RefCell::new(HashMap::new()), func: f, } } pub fn lookup(&self, i: I) -> Rc<O> { if !self.store.borrow().contains_key(&i) { let ref func = self.func; let new_val = func(se...
new
identifier_name
memorize.rs
use std::collections::HashMap; use std::cmp::Eq; use std::hash::Hash; use std::cell::RefCell; use std::rc::Rc; pub struct Memorizer<I, O> { store: RefCell<HashMap<I, Rc<O>>>, func: Box<Fn(&Memorizer<I, O>, &I) -> O>, } impl<I: Clone + Hash + Eq, O> Memorizer<I, O> { pub fn new(f: Box<Fn(&Self, &I) -> O>) ...
} } pub fn lookup(&self, i: I) -> Rc<O> { if !self.store.borrow().contains_key(&i) { let ref func = self.func; let new_val = func(self, &i); self.store.borrow_mut().insert(i.clone(), Rc::new(new_val)); } self.store.borrow().get(&i).unwrap().clo...
Memorizer { store: RefCell::new(HashMap::new()), func: f,
random_line_split
memorize.rs
use std::collections::HashMap; use std::cmp::Eq; use std::hash::Hash; use std::cell::RefCell; use std::rc::Rc; pub struct Memorizer<I, O> { store: RefCell<HashMap<I, Rc<O>>>, func: Box<Fn(&Memorizer<I, O>, &I) -> O>, } impl<I: Clone + Hash + Eq, O> Memorizer<I, O> { pub fn new(f: Box<Fn(&Self, &I) -> O>) ...
self.store.borrow().get(&i).unwrap().clone() } }
{ let ref func = self.func; let new_val = func(self, &i); self.store.borrow_mut().insert(i.clone(), Rc::new(new_val)); }
conditional_block
CheckButton.py
#!/usr/bin/env python import sys sys.path.insert(0, "../..") DEBUG = 0 if len(sys.argv) > 1:
from Kiwi.initgtk import gtk from Kiwi.Proxies import Proxy from Kiwi.Models import Model class Foo(Model): A = 1 B = 0 class CheckProxy(Proxy): widgets = [":B", ":A"] def __init__(self, model): self._build() Proxy.__init__(self, model, delete_handler=gtk.mainquit) gtk.idle_a...
DEBUG = 1
conditional_block
CheckButton.py
#!/usr/bin/env python import sys sys.path.insert(0, "../..") DEBUG = 0 if len(sys.argv) > 1: DEBUG = 1 from Kiwi.initgtk import gtk from Kiwi.Proxies import Proxy from Kiwi.Models import Model class Foo(Model): A = 1 B = 0 class CheckProxy(Proxy): widgets = [":B", ":A"] def __init__(self, model)...
c.A.clicked() c.B.clicked() assert f.A == 0, f.A assert f.B == 1, f.B if DEBUG: c.show_all_and_loop(); print f.__dict__ print "ToggleButton OK"
assert f.B == 0, f.B
random_line_split
CheckButton.py
#!/usr/bin/env python import sys sys.path.insert(0, "../..") DEBUG = 0 if len(sys.argv) > 1: DEBUG = 1 from Kiwi.initgtk import gtk from Kiwi.Proxies import Proxy from Kiwi.Models import Model class Foo(Model): A = 1 B = 0 class CheckProxy(Proxy): widgets = [":B", ":A"] def __init__(self, model)...
(self): self.win = gtk.Window() self.A = gtk.ToggleButton("This is A") self.B = gtk.ToggleButton("This is B") vbox = gtk.VBox() vbox.add(self.A) vbox.add(self.B) self.win.add(vbox) f = Foo() c = CheckProxy(f) assert f.A == 1 assert f.B == 0 c.A.clicked() c.B.clic...
_build
identifier_name
CheckButton.py
#!/usr/bin/env python import sys sys.path.insert(0, "../..") DEBUG = 0 if len(sys.argv) > 1: DEBUG = 1 from Kiwi.initgtk import gtk from Kiwi.Proxies import Proxy from Kiwi.Models import Model class Foo(Model): A = 1 B = 0 class CheckProxy(Proxy): widgets = [":B", ":A"] def __init__(self, model)...
class ToggleProxy(CheckProxy): def _build(self): self.win = gtk.Window() self.A = gtk.ToggleButton("This is A") self.B = gtk.ToggleButton("This is B") vbox = gtk.VBox() vbox.add(self.A) vbox.add(self.B) self.win.add(vbox) f = Foo() c = CheckProxy(f) assert ...
self.win = gtk.Window() self.A = gtk.CheckButton("This is A") self.B = gtk.CheckButton("This is B") vbox = gtk.VBox() vbox.add(self.A) vbox.add(self.B) self.win.add(vbox)
identifier_body
Subheader.js
'use strict'; import React, {PureComponent} from 'react'; import {StyleSheet, View, Text} from 'react-native'; import withMaterialTheme from './styles/withMaterialTheme'; import {withMeasurementForwarding} from './util'; import * as typo from './styles/typo'; import shades from './styles/shades'; /** * Section headin...
() { const { materialTheme, style, textStyle, inset, text, lines, secondary, color: colorOverride, dark, light, ...textProps } = this.props; let color; if ( colorOverride ) { color = colorOverride; } else if ( dark || light ) { const theme = dark ? 'dark' : 'light'; ...
render
identifier_name
Subheader.js
'use strict'; import React, {PureComponent} from 'react'; import {StyleSheet, View, Text} from 'react-native'; import withMaterialTheme from './styles/withMaterialTheme'; import {withMeasurementForwarding} from './util'; import * as typo from './styles/typo'; import shades from './styles/shades'; /** * Section headin...
lines: 1, }; render() { const { materialTheme, style, textStyle, inset, text, lines, secondary, color: colorOverride, dark, light, ...textProps } = this.props; let color; if ( colorOverride ) { color = colorOverride; } else if ( dark || light ) { const theme = dark...
random_line_split
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Bor...
use app_units::Au; use cssparser::ToCss; use std::fmt; impl ToCss for SpecifiedValue { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } #[inline] pub fn parse(_context: &Parser...
${helpers.predefined_type("border-%s-style" % side, "BorderStyle", "specified::BorderStyle::none", need_clone=True)} % endfor % for side in ["top", "right", "bottom", "left"]: <%helpers:longhand name="border-${side}-width">
random_line_split
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Bor...
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { self.0.to_css(dest) } } #[inline] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input)....
to_css
identifier_name
border.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% from data import Method %> <% data.new_style_struct("Bor...
} #[inline] pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { specified::parse_border_width(input).map(SpecifiedValue) } #[derive(Debug, Clone, PartialEq, HeapSizeOf)] pub struct Specifi...
{ self.0.to_css(dest) }
identifier_body
init_history_length.py
from ert_gui.models.ert_connector import ErtConnector from ert_gui.models.mixins import SpinnerModelMixin class HistoryLengthModel(ErtConnector, SpinnerModelMixin): def __init__(self): self.__value = self.getMaxValue() super(HistoryLengthModel, self).__init__() #todo: notify when the his...
""" @rtype: int """ return self.getHistoryLength() def getSpinnerValue(self): return self.__value def setSpinnerValue(self, value): self.__value = value self.observable().notify(SpinnerModelMixin.SPINNER_VALUE_CHANGED_EVENT) def setToMax(self): self.setSpin...
random_line_split
init_history_length.py
from ert_gui.models.ert_connector import ErtConnector from ert_gui.models.mixins import SpinnerModelMixin class HistoryLengthModel(ErtConnector, SpinnerModelMixin):
def setToMax(self): self.setSpinnerValue(self.getMaxValue()) def setToMin(self): self.setSpinnerValue(self.getMinValue()) def getHistoryLength(self): """ @rtype: int """ return self.ert().getHistoryLength()
def __init__(self): self.__value = self.getMaxValue() super(HistoryLengthModel, self).__init__() #todo: notify when the history length changes... def getMinValue(self): """ @rtype: int """ return 0 def getMaxValue(self): """ @rtype: int """ return self....
identifier_body
init_history_length.py
from ert_gui.models.ert_connector import ErtConnector from ert_gui.models.mixins import SpinnerModelMixin class HistoryLengthModel(ErtConnector, SpinnerModelMixin): def __init__(self): self.__value = self.getMaxValue() super(HistoryLengthModel, self).__init__() #todo: notify when the his...
(self): self.setSpinnerValue(self.getMaxValue()) def setToMin(self): self.setSpinnerValue(self.getMinValue()) def getHistoryLength(self): """ @rtype: int """ return self.ert().getHistoryLength()
setToMax
identifier_name
pgpactions.py
import datetime import threading import requests import db import cfg from skier import pgp from cfg import API_VERSION, SKIER_VERSION def import_key(keyserver: str, keyid: str):
# Check the API version to make sure we're compatible. if js['api_version'] == API_VERSION: is_skier = True except: pass # Lookup the key. data = None if not is_skier: name = keyserver + "/pks/lookup" params = {"op": "get", "search": keyid,...
""" Attempts to import a key from the keyserver. :param keyserver: The keyserver to import from. :param keyid: The Key ID to import. :return: One of many codes: - 0: Success - -1: key not found - -2: Could not connect to keyserver - -3: Invalid key - -4: A...
identifier_body
pgpactions.py
import datetime import threading import requests import db import cfg from skier import pgp from cfg import API_VERSION, SKIER_VERSION def import_key(keyserver: str, keyid: str): """ Attempts to import a key from the keyserver. :param keyserver: The keyserver to import from. :param keyid: The Key ID...
# This makes even less sense continue if not r.headers["content-type"] == "application/json": # This MAKES EVEN LESS SENSE continue keydata = r.json()["key"] pgp.add_pgp_key(keydata) # Update the synched table. new_synch = db.Synch() ...
# what continue if r.status_code != 200:
random_line_split
pgpactions.py
import datetime import threading import requests import db import cfg from skier import pgp from cfg import API_VERSION, SKIER_VERSION def import_key(keyserver: str, keyid: str): """ Attempts to import a key from the keyserver. :param keyserver: The keyserver to import from. :param keyid: The Key ID...
else: dt = synch.synch_time print("Synching since {}".format(dt)) # Open up our servers list. synch_servers = cfg.cfg.config.keyservers_synch # Contact them, one-by-one. synch_dict = {} for server in synch_servers: assert isinstance(server, str) if not server.startsw...
dt = datetime.datetime(1970, 1, 1, 1, 0, 0)
conditional_block
pgpactions.py
import datetime import threading import requests import db import cfg from skier import pgp from cfg import API_VERSION, SKIER_VERSION def
(keyserver: str, keyid: str): """ Attempts to import a key from the keyserver. :param keyserver: The keyserver to import from. :param keyid: The Key ID to import. :return: One of many codes: - 0: Success - -1: key not found - -2: Could not connect to keyserver ...
import_key
identifier_name
__init__.py
# Resource Representation reference dictionary (METS USE) USE = { 'high_res': 1, 'thumbnail': 2, 'med_res': 3, 'ocr': 4, 'bounding_box': 5, 'transcription': 6, 'translation': 7, 'zoom': 8, 'cdx': 9, 'square': 10, } # View method for mimetypes VIEW_TYPE_MIMETYPES = { 'image/p...
None: 'file', } EMAIL_REGEX = r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}' # Metadata location tuple. Used to specify potential source systems # for metadata files. METADATA_LOCATIONS = () # Static file location tuple. Used to specify potential source # systems for static files. STATIC_FILE_LOCATIONS = ()
'application/zip': 'file', 'video/x-flv': 'video', 'video/mp4': 'video',
random_line_split
stream.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Represents a token stream. use std::fmt; use std::convert::Into; use std::ops::Deref; use engine::parser::token::{self, Token, Type}; use template; use...
pub fn iter(&'a self) -> Iter<'a> { (&self.items).into_iter() } pub fn deref_iter(&'a self) -> DerefIter<'a> { DerefIter { items: (&self.items).into_iter() } } } impl<'a> fmt::Display for Stream<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { let v...
{ &self.items }
identifier_body
stream.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Represents a token stream. use std::fmt; use std::convert::Into; use std::ops::Deref; use engine::parser::token::{self, Token, Type}; use template; use...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, " StreamDump{{ template: {template:?}, items: {items:?}}}", template = self.template_str, items = self.items_str) } } // TODO: add another token_iter() to the main implementation [using .map(|i| i.into()...
fmt
identifier_name
stream.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Represents a token stream. use std::fmt; use std::convert::Into; use std::ops::Deref; use engine::parser::token::{self, Token, Type}; use template; use...
Ok(&self) } else { traced_err!(TokenError::UnexpectedTokenAtItem { reason: reason, expected: <token::Pattern as Dump>::dump(&pattern), found: self.dump(), }) } } } pub type ItemDump = Item; // may change as soon as ...
where T: token::Pattern + 'static { if pattern.matches(self.token()) {
random_line_split
application-insights.ts
export interface AIMonthlySummary { successCount: number; failedCount: number; } export interface AIInvocationTrace { timestamp: string; timestampFriendly: string; id: string; name: string; success: boolean;
resultCode: string; duration: number; operationId: string; invocationId: string; } export interface AIInvocationTraceHistory { rowId: number; timestamp: string; timestampFriendly: string; message: string; logLevel: string; } export interface AIQueryResult { tables: AIQueryResultTabl...
random_line_split
plot_precession.py
#!/usr/bin/env python3 import numpy as np, pylab, tkinter import matplotlib.pyplot as plt from scipy.optimize import curve_fit from decimal import * import sys, string, os argv = sys.argv if len(argv) != 3:
lammps_file = sys.argv[1] llg_file = sys.argv[2] t_lmp,Sx_lmp,Sy_lmp,Sz_lmp,e_lmp = np.loadtxt(lammps_file,skiprows=0, usecols=(1,2,3,4,7),unpack=True) t_llg,Sx_llg,Sy_llg,Sz_llg,e_llg = np.loadtxt(llg_file,skiprows=0, usecols=(0,1,2,3,4),unpack=True) plt.figure() plt.subplot(411) plt.ylabel('Sx') plt.plot(t_lmp, S...
print("Syntax: ./plot_precession.py res_lammps.dat res_llg.dat") sys.exit()
conditional_block
plot_precession.py
#!/usr/bin/env python3 import numpy as np, pylab, tkinter import matplotlib.pyplot as plt from scipy.optimize import curve_fit from decimal import * import sys, string, os argv = sys.argv if len(argv) != 3: print("Syntax: ./plot_precession.py res_lammps.dat res_llg.dat") sys.exit()
t_lmp,Sx_lmp,Sy_lmp,Sz_lmp,e_lmp = np.loadtxt(lammps_file,skiprows=0, usecols=(1,2,3,4,7),unpack=True) t_llg,Sx_llg,Sy_llg,Sz_llg,e_llg = np.loadtxt(llg_file,skiprows=0, usecols=(0,1,2,3,4),unpack=True) plt.figure() plt.subplot(411) plt.ylabel('Sx') plt.plot(t_lmp, Sx_lmp, 'b-', label='LAMMPS') plt.plot(t_llg, Sx_llg,...
lammps_file = sys.argv[1] llg_file = sys.argv[2]
random_line_split
train_ptb_dep_sa_albert_topk.py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-03-07 23:48 from hanlp.metrics.parsing import conllx_eval from hanlp.datasets.parsing.ptb import PTB_SD330_DEV, PTB_SD330_TRAIN, PTB_SD330_TEST, PTB_TOKEN_MAPPING from hanlp.components.parsers.biaffine_parser_tf import BiaffineTransformerDependencyParserTF, \ St...
# print(f'Official UAS: {uas:.4f} LAS: {las:.4f}') print(f'Model saved in {save_dir}')
random_line_split
RegisterService.ts
import "rxjs/add/operator/toPromise"; import {Http, Headers} from "@angular/http"; import {RestEndpointConfig} from "./configuration/RestEndpointConfig"; import {Injectable} from "@angular/core"; import {UserDto} from "../dto/UserDto"; @Injectable() export class RegisterService { private headers: Headers; constr...
private handleError(error: any): Promise<any> { console.error('An error occurred while trying to login', error); return Promise.reject(error.message || error); } }
{ let userJson = JSON.stringify(user); return this.http.post(this.restEndpointConfig.server + "/register", userJson, {headers: this.headers}) .toPromise() .then(response => response.json() as UserDto) .catch(this.handleError); }
identifier_body
RegisterService.ts
import "rxjs/add/operator/toPromise"; import {Http, Headers} from "@angular/http"; import {RestEndpointConfig} from "./configuration/RestEndpointConfig"; import {Injectable} from "@angular/core"; import {UserDto} from "../dto/UserDto"; @Injectable() export class RegisterService { private headers: Headers;
this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.headers.append('Accept', 'application/json'); } public register(user: UserDto): Promise<UserDto> { let userJson = JSON.stringify(user); return this.http.post(this.restEndpointConfig.server + "/register",...
constructor(private http: Http, private restEndpointConfig: RestEndpointConfig) {
random_line_split
RegisterService.ts
import "rxjs/add/operator/toPromise"; import {Http, Headers} from "@angular/http"; import {RestEndpointConfig} from "./configuration/RestEndpointConfig"; import {Injectable} from "@angular/core"; import {UserDto} from "../dto/UserDto"; @Injectable() export class RegisterService { private headers: Headers;
(private http: Http, private restEndpointConfig: RestEndpointConfig) { this.headers = new Headers(); this.headers.append('Content-Type', 'application/json'); this.headers.append('Accept', 'application/json'); } public register(user: UserDto): Promise<UserDto> { let userJson = JSON.stringify(user); ...
constructor
identifier_name
test_gravmag_euler.py
from __future__ import division import numpy as np from fatiando.gravmag.euler import Classic, ExpandingWindow, MovingWindow from fatiando.gravmag import sphere, fourier from fatiando.mesher import Sphere from fatiando import utils, gridder model = None xp, yp, zp = None, None, None inc, dec = None, None struct_ind = ...
(): global model, x, y, z, inc, dec, struct_ind, field, xderiv, yderiv, \ zderiv, base, pos inc, dec = -30, 50 pos = np.array([1000, 1000, 200]) model = Sphere(pos[0], pos[1], pos[2], 1, #{'magnetization':utils.ang2vec(100, 25, -10)}) {'magnetization':100...
setup
identifier_name
test_gravmag_euler.py
from __future__ import division import numpy as np from fatiando.gravmag.euler import Classic, ExpandingWindow, MovingWindow from fatiando.gravmag import sphere, fourier from fatiando.mesher import Sphere from fatiando import utils, gridder model = None xp, yp, zp = None, None, None inc, dec = None, None struct_ind = ...
inc, dec = -30, 50 pos = np.array([1000, 1000, 200]) model = Sphere(pos[0], pos[1], pos[2], 1, #{'magnetization':utils.ang2vec(100, 25, -10)}) {'magnetization':10000}) struct_ind = 3 shape = (128, 128) x, y, z = gridder.regular((0, 3000, 0, 3000), shape, z=-...
def setup(): global model, x, y, z, inc, dec, struct_ind, field, xderiv, yderiv, \ zderiv, base, pos
random_line_split
test_gravmag_euler.py
from __future__ import division import numpy as np from fatiando.gravmag.euler import Classic, ExpandingWindow, MovingWindow from fatiando.gravmag import sphere, fourier from fatiando.mesher import Sphere from fatiando import utils, gridder model = None xp, yp, zp = None, None, None inc, dec = None, None struct_ind = ...
def test_euler_classic_movingwindow_sphere_mag(): "gravmag.euler.MovingWindow w Classic for sphere model + magnetic data" euler = MovingWindow( Classic(x, y, z, field, xderiv, yderiv, zderiv, struct_ind), windows=[10, 10], size=(1000, 1000), keep=0.2).fit() for b in euler.baselevel...
"gravmag.euler.ExpandingWindow w Classic for sphere model + magnetic data" euler = ExpandingWindow( Classic(x, y, z, field, xderiv, yderiv, zderiv, struct_ind), center=[1000, 1000], sizes=np.linspace(100, 2000, 20)).fit() assert (base - euler.baselevel_)/base <= precision, \ ...
identifier_body
test_gravmag_euler.py
from __future__ import division import numpy as np from fatiando.gravmag.euler import Classic, ExpandingWindow, MovingWindow from fatiando.gravmag import sphere, fourier from fatiando.mesher import Sphere from fatiando import utils, gridder model = None xp, yp, zp = None, None, None inc, dec = None, None struct_ind = ...
assert np.all((pos - c)/pos <= precision), \ 'position: %s estimated: %s' % (str(pos), str(c))
conditional_block
login.rs
use std::io::prelude::*; use std::io; use cargo::ops; use cargo::core::{SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CargoError, CliResult, CargoResultExt, Config}; #[derive(Deserialize)] pub struct Options { flag_host: Option<String>, arg_token: Option<String>, flag_verbose: u...
let src = SourceId::crates_io(config)?; let mut src = RegistrySource::remote(&src, config); src.update()?; let config = src.config()?.unwrap(); options.flag_host.clone().unwrap_or(config.api.unwrap()) } ...
{ config.configure(options.flag_verbose, options.flag_quiet, &options.flag_color, options.flag_frozen, options.flag_locked, &options.flag_z)?; if options.flag_registry.is_some() && !config.cli_unstable().un...
identifier_body
login.rs
use std::io::prelude::*; use std::io; use cargo::ops; use cargo::core::{SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CargoError, CliResult, CargoResultExt, Config}; #[derive(Deserialize)] pub struct Options { flag_host: Option<String>, arg_token: Option<String>, flag_verbose: u...
pub const USAGE: &'static str = " Save an api token from the registry locally. If token is not specified, it will be read from stdin. Usage: cargo login [options] [<token>] Options: -h, --help Print this message --host HOST Host to set the token for -v, --verbose ... ...
#[serde(rename = "flag_Z")] flag_z: Vec<String>, flag_registry: Option<String>, }
random_line_split
login.rs
use std::io::prelude::*; use std::io; use cargo::ops; use cargo::core::{SourceId, Source}; use cargo::sources::RegistrySource; use cargo::util::{CargoError, CliResult, CargoResultExt, Config}; #[derive(Deserialize)] pub struct
{ flag_host: Option<String>, arg_token: Option<String>, flag_verbose: u32, flag_quiet: Option<bool>, flag_color: Option<String>, flag_frozen: bool, flag_locked: bool, #[serde(rename = "flag_Z")] flag_z: Vec<String>, flag_registry: Option<String>, } pub const USAGE: &'static str...
Options
identifier_name
index.d.ts
boolean; } type NodeSettings<TSets> = { [K in keyof TSets]: NodeSetting<TSets[K]>; }; interface NodeCredential { type: 'text' | 'password'; } type NodeCredentials<TCreds> = { [K in keyof TCreds]: NodeCredential; }; interface NodeAPINodes { /** ...
* Log an INFO level message */ log(msg: any): void; /** * Log a WARN level message */ warn(msg: any): void; /** * Log an ERROR level message */ error(logMessage: any, msg?: NodeMessage): void; /** * Log an DEB...
receive(msg?: NodeMessage): void; /**
random_line_split
stitching.js
var taxi = require('..'); var chromedriver = require('chromedriver'); var fs = require('fs'); var user = process.env.SAUCE_USERNAME; var accessKey = process.env.SAUCE_ACCESS_KEY;
{ url:'http://localhost:9515/', capabilities: { browserName:'chrome' }, beforeFn: function () { chromedriver.start(); }, afterFn: function () { chromedriver.stop() } }, { url:'http://localhost:9517/', capabilities: { browserName:'phantomjs', browserVersion:'1.9.8' } }, { url:'http://localhost:4444/wd/hub', capabili...
var sauceLabsUrl = "http://" + user + ":" + accessKey + "@ondemand.saucelabs.com/wd/hub"; var tests = [
random_line_split
stitching.js
var taxi = require('..'); var chromedriver = require('chromedriver'); var fs = require('fs'); var user = process.env.SAUCE_USERNAME; var accessKey = process.env.SAUCE_ACCESS_KEY; var sauceLabsUrl = "http://" + user + ":" + accessKey + "@ondemand.saucelabs.com/wd/hub"; var tests = [ { url:'http://localhost:9515/', c...
}, completeFn: function () { // When it has a "masthead", then display it again if (document.getElementById('masthead')) { document.getElementById('masthead').style.display = ''; } }, // Here is a list of areas that should be blocked-out blockOuts: [ // Block-out all text-boxes ...
{ document.getElementById('masthead').style.display = 'none'; }
conditional_block
p2.py
# Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million...
if n % 2 == 0: sum += n return sum print problem2(4000000)
break
conditional_block
p2.py
# Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million...
def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)
previous, current = 0, 1 while True: previous, current = current, previous + current yield current
identifier_body
p2.py
# Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million...
def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)
while True: previous, current = current, previous + current yield current
random_line_split
p2.py
# Even Fibonacci numbers # Problem 2 # Each new term in the Fibonacci sequence is generated by adding the # previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed # four million...
(): previous, current = 0, 1 while True: previous, current = current, previous + current yield current def problem2(bound): sum = 0 for n in fibs(): if n >= bound: break if n % 2 == 0: sum += n return sum print problem2(4000000)
fibs
identifier_name
test_parentHook2to3.py
""" Test upgrading L{_SubSchedulerParentHook} from version 2 to 3. """ from axiom.test.historic.stubloader import StubbedTest from axiom.scheduler import _SubSchedulerParentHook from axiom.substore import SubStore from axiom.dependency import _DependencyConnector class SubSchedulerParentHookUpgradeTests(StubbedTest...
def test_uninstalled(self): """ The record of the installation of L{_SubSchedulerParentHook} on the store is deleted in the upgrade to schema version 4. """ self.assertEquals( list(self.store.query( _DependencyConnector, _De...
random_line_split
test_parentHook2to3.py
""" Test upgrading L{_SubSchedulerParentHook} from version 2 to 3. """ from axiom.test.historic.stubloader import StubbedTest from axiom.scheduler import _SubSchedulerParentHook from axiom.substore import SubStore from axiom.dependency import _DependencyConnector class SubSchedulerParentHookUpgradeTests(StubbedTes...
(self): """ The record of the installation of L{_SubSchedulerParentHook} on the store is deleted in the upgrade to schema version 4. """ self.assertEquals( list(self.store.query( _DependencyConnector, _DependencyConnector.instal...
test_uninstalled
identifier_name
test_parentHook2to3.py
""" Test upgrading L{_SubSchedulerParentHook} from version 2 to 3. """ from axiom.test.historic.stubloader import StubbedTest from axiom.scheduler import _SubSchedulerParentHook from axiom.substore import SubStore from axiom.dependency import _DependencyConnector class SubSchedulerParentHookUpgradeTests(StubbedTes...
d.addCallback(cbSetUp) return d def test_attributesCopied(self): """ The only attribute of L{_SubSchedulerParentHook} which still exists at the current version, version 4, C{subStore}, ought to have been copied over. """ self.assertIdentical( ...
self.hook = self.store.findUnique(_SubSchedulerParentHook)
identifier_body
latest.rs
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors // See the README.md file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// except according to those terms. extern crate futures; extern crate hyper; extern crate hyper_tls; extern crate tokio_core; extern crate xkcd; use hyper::Client; use hyper_tls::HttpsConnector; use tokio_core::reactor::Core; fn main() { let mut core = Core::new().unwrap(); let client = Client::configure() ...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
latest.rs
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors // See the README.md file at the top-level directory of this distribution. // // 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.o...
{ let mut core = Core::new().unwrap(); let client = Client::configure() .connector(HttpsConnector::new(4, &core.handle()).unwrap()) .build(&core.handle()); // Retrieve the latest comic. let work = xkcd::comics::latest(&client); let latest_comic = core.run(work).unwrap(); println...
identifier_body