file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
test_registry.py
#!/usr/bin/env python """ """ # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pyhmsa_gui.util.testcase import TestCaseQApp, QTest from pyhmsa_gui.util.registry import \ (iter_entry_points, iter_condition_widget_classes, iter_condition_widgets, ite...
pass def testiter_exporters(self): pass def testiter_preferences_widget_classes(self): pass if __name__ == '__main__': #pragma: no cover logging.getLogger().setLevel(logging.DEBUG) unittest.main()
def testiter_importers(self): pass def testiter_exporter_classes(self):
random_line_split
test_registry.py
#!/usr/bin/env python """ """ # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pyhmsa_gui.util.testcase import TestCaseQApp, QTest from pyhmsa_gui.util.registry import \ (iter_entry_points, iter_condition_widget_classes, iter_condition_widgets, ite...
(self): TestCaseQApp.tearDown(self) def testiter_entry_points(self): pass def testiter_condition_widget_classes(self): pass def testiter_condition_widgets(self): pass def testiter_datum_widget_classes(self): pass def testiter_datum_widgets(self): ...
tearDown
identifier_name
test_registry.py
#!/usr/bin/env python """ """ # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pyhmsa_gui.util.testcase import TestCaseQApp, QTest from pyhmsa_gui.util.registry import \ (iter_entry_points, iter_condition_widget_classes, iter_condition_widgets, ite...
logging.getLogger().setLevel(logging.DEBUG) unittest.main()
conditional_block
test_registry.py
#!/usr/bin/env python """ """ # Standard library modules. import unittest import logging # Third party modules. # Local modules. from pyhmsa_gui.util.testcase import TestCaseQApp, QTest from pyhmsa_gui.util.registry import \ (iter_entry_points, iter_condition_widget_classes, iter_condition_widgets, ite...
if __name__ == '__main__': #pragma: no cover logging.getLogger().setLevel(logging.DEBUG) unittest.main()
pass
identifier_body
frame.py
# ----------------------------------------------------------------------------- # # -*- coding: utf-8 -*- # # phlox-libdc1394/dc1394/frame.py # # Copyright (C) 2016, by Matthias Yang Chen <matthias_cy@outlook.com> # All rights reserved. # # phlox-libdc1394 is free software: you can redistribute it and/or modify it # un...
.. note:: Corrupt frames still need to be enqueued with `enqueue` when no longer needed by the user. """ return bool(dll.dc1394_capture_is_frame_corrupt(self._cam, self._frame)) def to_rgb(self): """ Convert the image to an RGB image. Array sha...
detect corruption also varies between platforms.
random_line_split
frame.py
# ----------------------------------------------------------------------------- # # -*- coding: utf-8 -*- # # phlox-libdc1394/dc1394/frame.py # # Copyright (C) 2016, by Matthias Yang Chen <matthias_cy@outlook.com> # All rights reserved. # # phlox-libdc1394 is free software: you can redistribute it and/or modify it # un...
def enqueue(self): """ Returns a frame to the ring buffer once it has been used. This method is also called implicitly on ``del``. Only call this method on the original frame obtained from Camera.dequeue` and not on its views, new-from-templates or ...
""" Finalize the new Image class array. If called with an image object, inherit the properties of that image. """ if img is None: return # do not inherit _frame and _cam since we also get called on copy() # and should not hold references to the fra...
identifier_body
frame.py
# ----------------------------------------------------------------------------- # # -*- coding: utf-8 -*- # # phlox-libdc1394/dc1394/frame.py # # Copyright (C) 2016, by Matthias Yang Chen <matthias_cy@outlook.com> # All rights reserved. # # phlox-libdc1394 is free software: you can redistribute it and/or modify it # un...
if self._frame is not None: dll.dc1394_capture_enqueue(self._cam, self._frame) self._frame = None self._cam = None # from contextlib iport closing # with closing(camera.dequeue()) as im: # do stuff with im close = enqueue def __del__(self): tr...
raise AttributeError("can only enqueue the original frame")
conditional_block
frame.py
# ----------------------------------------------------------------------------- # # -*- coding: utf-8 -*- # # phlox-libdc1394/dc1394/frame.py # # Copyright (C) 2016, by Matthias Yang Chen <matthias_cy@outlook.com> # All rights reserved. # # phlox-libdc1394 is free software: you can redistribute it and/or modify it # un...
(self): try: self.enqueue() except AttributeError: pass @property def corrupt(self): """ Whether this frame corrupt. Returns ``True`` if the given frame has been detected to be corrupt (missing data, corrupted data, overrun buffer, etc.) ...
__del__
identifier_name
browsercontext.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::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Refl...
(&mut self) { let win = self.active_window().root(); let page = win.deref().page(); let js_info = page.js_info(); let handler = js_info.as_ref().unwrap().dom_static.windowproxy_handler; assert!(handler.deref().is_not_null()); let parent = win.deref().reflector().get_jso...
create_window_proxy
identifier_name
browsercontext.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::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Refl...
pub fn active_window(&self) -> Temporary<Window> { let doc = self.active_document().root(); Temporary::new(doc.deref().window.clone()) } pub fn window_proxy(&self) -> *mut JSObject { assert!(self.window_proxy.deref().is_not_null()); *self.window_proxy } fn create_...
{ Temporary::new(self.history[self.active_index].document.clone()) }
identifier_body
browsercontext.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::js::{JS, JSRef, Temporary}; use dom::bindings::trace::Traceable; use dom::bindings::utils::Refl...
use dom::window::Window; use js::jsapi::JSObject; use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps}; use js::rust::with_compartment; use libc::c_void; use std::ptr; #[allow(raw_pointer_deriving)] #[deriving(Encodable)] pub struct BrowserContext { history: Vec<SessionHistoryEntry>, active_inde...
random_line_split
cereconf_local.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2003-2018 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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 2...
from Cerebrum.default_config import * CEREBRUM_DATABASE_NAME = os.getenv('DB_NAME') CEREBRUM_DATABASE_CONNECT_DATA['user'] = os.getenv('DB_USER') CEREBRUM_DATABASE_CONNECT_DATA['table_owner'] = os.getenv('DB_USER') CEREBRUM_DATABASE_CONNECT_DATA['host'] = os.getenv('DB_HOST') CEREBRUM_DATABASE_CONNECT_DATA['table_owne...
import os
random_line_split
job.ts
import * as CronDate from 'cron-parser/lib/date'; import * as cronParser from "cron-parser"; import * as lt from "long-timeout"; import * as util from "./util"; import RecurrenceRule from "./recurrence-rule"; import { EventEmitter } from "events"; import SortedArray from "./sorted-array"; export type InvocationArray =...
(rule: RecurrenceRule | any, job: Job, prevDate: Date, endDate: Date): Invocation { prevDate = prevDate || new Date(); const date = rule instanceof RecurrenceRule ? rule.nextInvocationDate(prevDate) : rule.next(); if (date === null) { return null; } if (endDate instanceof Date && date.getTim...
scheduleNextRecurrence
identifier_name
job.ts
import * as CronDate from 'cron-parser/lib/date'; import * as cronParser from "cron-parser"; import * as lt from "long-timeout"; import * as util from "./util"; import RecurrenceRule from "./recurrence-rule"; import { EventEmitter } from "events"; import SortedArray from "./sorted-array"; export type InvocationArray =...
reschedule(sched: ScheduleSpec): boolean { const cInvs = this.pendingInvocations.array.slice(); this.cancel(); if (this.schedule(sched)) { this.resetTriggeredJobs(); } else { this.pendingInvocations.array = cInvs; return false; } return true; } get nextInvocation(): Da...
{ let inv: Invocation, newInv: Invocation; for (let j = 0; j < this.pendingInvocations.length; j++) { inv = this.pendingInvocations.array[j]; jobMan.cancelInvocation(inv); } this.pendingInvocations.clear(); delete jobMan.scheduledJobs[this.name]; return true; }
identifier_body
job.ts
import * as CronDate from 'cron-parser/lib/date'; import * as cronParser from "cron-parser"; import * as lt from "long-timeout"; import * as util from "./util"; import RecurrenceRule from "./recurrence-rule"; import { EventEmitter } from "events"; import SortedArray from "./sorted-array"; export type InvocationArray =...
jobMan.cancelInvocation(inv); } this.pendingInvocations.clear(); delete jobMan.scheduledJobs[this.name]; return true; } reschedule(sched: ScheduleSpec): boolean { const cInvs = this.pendingInvocations.array.slice(); this.cancel(); if (this.schedule(sched)) { this.resetTrig...
inv = this.pendingInvocations.array[j];
random_line_split
job.ts
import * as CronDate from 'cron-parser/lib/date'; import * as cronParser from "cron-parser"; import * as lt from "long-timeout"; import * as util from "./util"; import RecurrenceRule from "./recurrence-rule"; import { EventEmitter } from "events"; import SortedArray from "./sorted-array"; export type InvocationArray =...
this.currentInvocation = this.invocations.array[0]; const job = this.currentInvocation.job; const cinv = this.currentInvocation; this.currentInvocation.timerID = this.runOnDate(this.currentInvocation.fireDate, function () { this.currentInvocationFinished(); const rule = cinv.re...
{ lt.clearTimeout(this.currentInvocation.timerID); this.currentInvocation.timerID = null; this.currentInvocation = null; }
conditional_block
htmlmodelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; use crate::dom::bindings::root::DomRoot; use ...
{ htmlelement: HTMLElement, } impl HTMLModElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } ...
HTMLModElement
identifier_name
htmlmodelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; use crate::dom::bindings::root::DomRoot; use ...
prefix: Option<Prefix>, document: &Document, ) -> HTMLModElement { HTMLModElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefi...
random_line_split
htmlmodelement.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; use crate::dom::bindings::root::DomRoot; use ...
}
{ Node::reflect_node( Box::new(HTMLModElement::new_inherited(local_name, prefix, document)), document, HTMLModElementBinding::Wrap, ) }
identifier_body
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn main()
{ println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending..."); match rx.try_recv() { Ok(_) => { println!("Terminating."); break; ...
identifier_body
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn main() { println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending...");
Ok(_) => { println!("Terminating."); break; } Err(_) => { println!("Working..."); thread::sleep(Duration::from_millis(500)); } } } }); thread::slee...
match rx.try_recv() {
random_line_split
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn
() { println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending..."); match rx.try_recv() { Ok(_) => { println!("Terminating."); break; ...
main
identifier_name
term.rs
use std::time::Duration; use std::thread; use std::sync::mpsc; use std::io::{self, BufRead}; fn main() { println!("Press enter to wake up the child thread"); let (tx, rx) = mpsc::channel(); thread::spawn(move || { loop { println!("Suspending..."); match rx.try_recv() { ...
Err(_) => { println!("Working..."); thread::sleep(Duration::from_millis(500)); } } } }); thread::sleep(Duration::from_millis(50000)); let _ = tx.send(()); // let mut line = String::new(); // let stdin...
{ println!("Terminating."); break; }
conditional_block
chunk.py
""" Chunk (N number of bytes at M offset to a source's beginning) provider. Primarily for file sources but usable by any iterator that has both seek and read( N ). """ import os import base64 import base import exceptions import logging log = logging.getLogger( __name__ ) # -----------------------------------------...
(gen. in bytes). """ super( ChunkDataProvider, self ).__init__( source, **kwargs ) self.chunk_size = int( chunk_size ) self.chunk_pos = int( chunk_index ) * self.chunk_size def validate_source( self, source ): """ Does the given source have both the metho...
`chunk_size` sections, this is the index of which section to return. :param chunk_size: how large are the desired chunks to return
random_line_split
chunk.py
""" Chunk (N number of bytes at M offset to a source's beginning) provider. Primarily for file sources but usable by any iterator that has both seek and read( N ). """ import os import base64 import base import exceptions import logging log = logging.getLogger( __name__ ) # -----------------------------------------...
class Base64ChunkDataProvider( ChunkDataProvider ): """ Data provider that yields chunks of base64 encoded data from its file. """ def encode( self, chunk ): """ Return chunks encoded in base 64. """ return base64.b64encode( chunk )
""" Data provider that yields chunks of data from its file. Note: this version does not account for lines and works with Binary datatypes. """ MAX_CHUNK_SIZE = 2 ** 16 DEFAULT_CHUNK_SIZE = MAX_CHUNK_SIZE settings = { 'chunk_index' : 'int', 'chunk_size' : 'int' } # ...
identifier_body
chunk.py
""" Chunk (N number of bytes at M offset to a source's beginning) provider. Primarily for file sources but usable by any iterator that has both seek and read( N ). """ import os import base64 import base import exceptions import logging log = logging.getLogger( __name__ ) # -----------------------------------------...
( self, source ): """ Does the given source have both the methods `seek` and `read`? :raises InvalidDataProviderSource: if not. """ source = super( ChunkDataProvider, self ).validate_source( source ) if( ( not hasattr( source, 'seek' ) ) or ( not hasattr( source, 'read' )...
validate_source
identifier_name
chunk.py
""" Chunk (N number of bytes at M offset to a source's beginning) provider. Primarily for file sources but usable by any iterator that has both seek and read( N ). """ import os import base64 import base import exceptions import logging log = logging.getLogger( __name__ ) # -----------------------------------------...
return source def __iter__( self ): # not reeeally an iterator per se self.__enter__() self.source.seek( self.chunk_pos, os.SEEK_SET ) chunk = self.encode( self.source.read( self.chunk_size ) ) yield chunk self.__exit__() def encode( self, chunk ): ...
raise exceptions.InvalidDataProviderSource( source )
conditional_block
AppShellRoutes.tsx
import React from 'react'; import { Navigate, Route, Routes } from 'react-router-dom'; import { RouteEnum } from 'types'; import { Account, Decks, Game, Player, Room, Server, Login, Logs, Initialize,
} from 'containers'; const AppShellRoutes = () => ( <div className="AppShell-routes overflow-scroll"> <Routes> <Route path='*' element={<Initialize />} /> <Route path={RouteEnum.ACCOUNT} element={<Account />} /> <Route path={RouteEnum.DECKS} element={<Decks />} /> <Route path={RouteEnum....
Unsupported
random_line_split
yanker.py
""" Yanker Usage: yanker [--threads=<tnum>] """ __version__ = '1.0.1' import Queue import threading import youtube_dl as ydl import pyperclip as clip import time from docopt import docopt class ErrLogger(object): def debug(self, msg): pass def warning(self, msg): pass def error(sel...
(self): recent = '' while not self.stopped: current = clip.paste() if recent != current: recent = current if current.startswith(('http://', 'https://',)) and current not in self.grabbed_urls: print 'Added: {}'.format(current) ...
run
identifier_name
yanker.py
""" Yanker Usage: yanker [--threads=<tnum>] """
import pyperclip as clip import time from docopt import docopt class ErrLogger(object): def debug(self, msg): pass def warning(self, msg): pass def error(self, msg): print msg class Worker(threading.Thread): def __init__(self, tasks): threading.Thread.__init__(self)...
__version__ = '1.0.1' import Queue import threading import youtube_dl as ydl
random_line_split
yanker.py
""" Yanker Usage: yanker [--threads=<tnum>] """ __version__ = '1.0.1' import Queue import threading import youtube_dl as ydl import pyperclip as clip import time from docopt import docopt class ErrLogger(object): def debug(self, msg): pass def warning(self, msg): pass def error(sel...
def run(self): while True: vid = self.tasks.get() vid.download() self.tasks.task_done() class Video: def progress(self, s): if s['status'] == 'finished': print 'Finished {}'.format(s['filename']) def __init__(self, url, opts={}): s...
threading.Thread.__init__(self) self.tasks = tasks self.daemon = True self.start()
identifier_body
yanker.py
""" Yanker Usage: yanker [--threads=<tnum>] """ __version__ = '1.0.1' import Queue import threading import youtube_dl as ydl import pyperclip as clip import time from docopt import docopt class ErrLogger(object): def debug(self, msg): pass def warning(self, msg): pass def error(sel...
elif current in self.grabbed_urls: print 'Already grabbed {}'.format(current) time.sleep(0.25) def run(): args = docopt(__doc__, version='Yanker {}'.format(__version__)) threads = args['--threads'] if not threads: threads = 2 else: threa...
print 'Added: {}'.format(current) self.grabbed_urls.add(current) self.queue.put(Video(current))
conditional_block
logging.rs
//! Module implementing logging for the application. //! //! This includes setting up log filtering given a verbosity value, //! as well as defining how the logs are being formatted to stderr. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use ansi_term::{Colour, Style}; use isatty; u...
() -> String { let utc_now = time::now().to_utc(); let mut logtime = format!("{}", utc_now.rfc3339()); // E.g.: 2012-02-22T14:53:18Z // Insert millisecond count before the Z. let millis = utc_now.tm_nsec / NANOS_IN_MILLISEC; logtime.pop(); format!("{}.{:04}Z", logtime, millis) } const NANOS_I...
format_log_time
identifier_name
logging.rs
//! Module implementing logging for the application. //! //! This includes setting up log filtering given a verbosity value, //! as well as defining how the logs are being formatted to stderr. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use ansi_term::{Colour, Style}; use isatty; u...
}
{ assert_eq!(NEGATIVE_VERBOSITY_LEVELS[0], POSITIVE_VERBOSITY_LEVELS[0]); assert!(NEGATIVE_VERBOSITY_LEVELS.contains(&FilterLevel::Off), "Verbosity levels don't allow to turn logging off completely"); }
identifier_body
logging.rs
//! Module implementing logging for the application. //! //! This includes setting up log filtering given a verbosity value, //! as well as defining how the logs are being formatted to stderr. use std::borrow::Cow; use std::collections::HashMap; use std::env; use std::io; use ansi_term::{Colour, Style}; use isatty; u...
Level::Info.as_usize() => Colour::Green.normal(), Level::Warning.as_usize() => Colour::Yellow.normal(), Level::Error.as_usize() => Colour::Red.normal(), Level::Critical.as_usize() => Colour::Purple.normal(), }; /// ANSI terminal style for the prefix (timestamp etc.) of a fine lo...
lazy_static! { /// Map of log levels to their ANSI terminal styles. // (Level doesn't implement Hash so it has to be usize). static ref TTY_LEVEL_STYLES: HashMap<usize, Style> = hashmap!{
random_line_split
spinner.js
/*! * Ext JS Library 3.3.0 * Copyright(c) 2006-2010 Ext JS, Inc. * licensing@extjs.com * http://www.extjs.com/license */ Ext.onReady(function(){ var simple = new Ext.FormPanel({ labelWidth: 40, // label settings here cascade unless overridden frame: true, title: 'Simple Form', b...
});
simple.render('form-ct');
random_line_split
up-to-date.py
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
test.subdir('layer', ['layer', 'aclock'], ['layer', 'aclock', 'qt_bug']) test.write('SConstruct', """\ import os aa=os.getcwd() env=Environment(tools=['default','expheaders','qt'],toolpath=[aa]) env["EXP_HEADER_ABS"]=os.path.join(os.getcwd(),'include') if not os.access(env["EXP_HEADER_ABS"],...
x ="External environment variable $QTDIR not set; skipping test(s).\n" test.skip_test(x)
conditional_block
up-to-date.py
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
# End: # vim: set expandtab tabstop=4 shiftwidth=4:
test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil
random_line_split
dimpleStepHor-cn.js
HTMLWidgets.widget({ name: 'dimpleStepHor-cn', type: 'output', initialize: function(el, width, height) { d3.select(el).append("div")
.attr("id","chartContainer") .attr("width", width) .attr("height", height); var svg = dimple.newSvg("#chartContainer", width, height); var data = [] var myChart = new dimple.chart(svg, data); return myChart }, renderValue: function(el, x, instance) { var myC...
random_line_split
loading.component.ts
import { Component, ViewChild, ElementRef, AfterViewInit, Input, ChangeDetectionStrategy } from '@angular/core' import { ColorsService } from '../../services/colors.service' @Component({ selector: 'eqm-loading', templateUrl: './loading.component.html', styleUrls: [ './loading.component.scss' ], changeDetection...
}
{ const path = this.wave.nativeElement // eslint-disable-next-line no-loss-of-precision const m = 0.512286623256592433 const w = 90 const h = 60 const a = h / 4 const y = h / 2 const pathData = [ 'M', w * 0, y + a / 2, 'c', a * m, 0, -(1 - a) * m, -a, a, -a, 's', -(1 ...
identifier_body
loading.component.ts
import { Component, ViewChild, ElementRef, AfterViewInit, Input, ChangeDetectionStrategy } from '@angular/core' import { ColorsService } from '../../services/colors.service' @Component({ selector: 'eqm-loading', templateUrl: './loading.component.html', styleUrls: [ './loading.component.scss' ], changeDetection...
implements AfterViewInit { @ViewChild('wave', { static: true }) wave!: ElementRef @Input() text?: string @Input() showText = true constructor ( public colors: ColorsService ) {} ngAfterViewInit () { const path = this.wave.nativeElement // eslint-disable-next-line no-loss-of-precision cons...
LoadingComponent
identifier_name
loading.component.ts
import { Component, ViewChild, ElementRef, AfterViewInit, Input, ChangeDetectionStrategy } from '@angular/core' import { ColorsService } from '../../services/colors.service' @Component({ selector: 'eqm-loading', templateUrl: './loading.component.html',
changeDetection: ChangeDetectionStrategy.OnPush }) export class LoadingComponent implements AfterViewInit { @ViewChild('wave', { static: true }) wave!: ElementRef @Input() text?: string @Input() showText = true constructor ( public colors: ColorsService ) {} ngAfterViewInit () { const path = thi...
styleUrls: [ './loading.component.scss' ],
random_line_split
principals.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from sqlalchemy.ext.declarative import declared_attr from indico.core.db import db from indico.core.db.sq...
(cls): return auto_table_args(cls, schema='categories') #: The ID of the acl entry id = db.Column( db.Integer, primary_key=True ) #: The ID of the associated event category_id = db.Column( db.Integer, db.ForeignKey('categories.categories.id'), nullabl...
__table_args__
identifier_name
principals.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from sqlalchemy.ext.declarative import declared_attr from indico.core.db import db from indico.core.db.sq...
class CategoryPrincipal(PrincipalPermissionsMixin, db.Model): __tablename__ = 'principals' principal_backref_name = 'in_category_acls' principal_for = 'Category' unique_columns = ('category_id',) allow_networks = True allow_category_roles = True @declared_attr def __table_args__(cls):...
random_line_split
principals.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from sqlalchemy.ext.declarative import declared_attr from indico.core.db import db from indico.core.db.sq...
return format_repr(self, 'id', 'category_id', 'principal', read_access=False, full_access=False, permissions=[])
identifier_body
nedb.spec.js
'use strict'; const fs = require('fs') , path = require('path') , expect = require('chai').expect , co = require('co') , nedb = require('nedb') , wrapper = require('co-nedb'); const sdeFixture = require('./fixtures/sde.json'); const sdeDbFile = path.join(__dirname, '../../lib/db/staticData.db'); const sdeM...
}); it('should let us query the collection', () => { expect(db).to.respondTo('findOne'); }); it('should correctly find a thing', () => { co(function * () { let thing = yield db.findOne({ id: 583 }); return expect(thing).to.equal(sdeFixture); }); }); }); describe('CCP Map SDE', ()...
random_line_split
easy-249.py
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 '''...
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" % (max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell])) if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices])
for sell_day in range(buy_day + 2, len(stock_prices)): profit = stock_prices[sell_day] - stock_prices[buy_day] if profit > max_profit: max_profit = profit max_buy = buy_day max_sell = sell_day
conditional_block
easy-249.py
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 '''...
if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices])
buy_day = 0 max_profit = 0 max_buy = 0 max_sell = 0 for buy_day in range(len(stock_prices) - 2): # maybe do a max(here) for sell_day in range(buy_day + 2, len(stock_prices)): profit = stock_prices[sell_day] - stock_prices[buy_day] if profit > max_profit: ...
identifier_body
easy-249.py
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 '''...
max_sell = sell_day print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" % (max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell])) if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices])
random_line_split
easy-249.py
#! /usr/bin/env python3 ''' given a list of stock price ticks for the day, can you tell me what trades I should make to maximize my gain within the constraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 '''...
(): parser = argparse.ArgumentParser(description='easy 249') parser.add_argument('stock_prices', action='store', nargs='+', help='prices of a given stock') return parser.parse_args() def stock(stock_prices): buy_day = 0 max_profit = 0 max_buy = 0 max_sell = 0 fo...
parse_args
identifier_name
kvstore.rs
//! test was move from base (it could not compile in base since its trait just change //! (bidirectional dependency)) //! TODO seems pretty useless : remove?? use keyval::KeyVal; use node::{Node,NodeID}; use peer::{Peer,Shadow}; use std::cmp::Eq; use std::cmp::PartialEq; use keyval::{Attachment,SettableAttachment}; u...
(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_auth_mode() } fn default_message_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_message_mode() } fn default_header_mode(&self) -> <Self::Shadow as Shadow>::ShadowMode { self.0.default_header_mode(...
default_auth_mode
identifier_name
kvstore.rs
//! test was move from base (it could not compile in base since its trait just change //! (bidirectional dependency)) //! TODO seems pretty useless : remove?? use keyval::KeyVal; use node::{Node,NodeID}; use peer::{Peer,Shadow}; use std::cmp::Eq; use std::cmp::PartialEq;
use rustc_serialize::{Encodable, Encoder, Decoder}; // Testing only nodeK, with key different from id #[derive(RustcDecodable,RustcEncodable,Debug,Clone)] struct NodeK2(Node,String); impl Eq for NodeK2 {} impl PartialEq<NodeK2> for NodeK2 { fn eq(&self, other: &NodeK2) -> bool { other.0 == self.0 && oth...
use keyval::{Attachment,SettableAttachment};
random_line_split
shared.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { MaterialModule } from '@app/material'; import { AboutDialogComponent } from './components/footer/about-dialog/about-d...
imports: [ CommonModule, ReactiveFormsModule, RouterModule, MaterialModule ], declarations: [ AboutDialogComponent, FooterComponent, HeaderComponent, PageComponent, SidenavComponent, CollapseDirective, CircularJsonPipe ], entryComponents: [ AboutDialogComponent ...
import { CircularJsonPipe } from './pipes/circular-json/circular-json.pipe'; @NgModule({
random_line_split
shared.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { MaterialModule } from '@app/material'; import { AboutDialogComponent } from './components/footer/about-dialog/about-d...
{ }
SharedModule
identifier_name
fms.py
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSProperty, AWSObject, Tags from .validators import json_checker, boolean class
(AWSProperty): props = { 'ACCOUNT': ([basestring], False), } class Policy(AWSObject): resource_type = "AWS::FMS::Policy" props = { 'DeleteAllPolicyResources': (boolean, False), 'ExcludeMap': (IEMap, False), 'ExcludeResourceTags': (boolean, True), 'IncludeMap': ...
IEMap
identifier_name
fms.py
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSProperty, AWSObject, Tags from .validators import json_checker, boolean
class IEMap(AWSProperty): props = { 'ACCOUNT': ([basestring], False), } class Policy(AWSObject): resource_type = "AWS::FMS::Policy" props = { 'DeleteAllPolicyResources': (boolean, False), 'ExcludeMap': (IEMap, False), 'ExcludeResourceTags': (boolean, True), 'I...
random_line_split
fms.py
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSProperty, AWSObject, Tags from .validators import json_checker, boolean class IEMap(AWSProperty):
class Policy(AWSObject): resource_type = "AWS::FMS::Policy" props = { 'DeleteAllPolicyResources': (boolean, False), 'ExcludeMap': (IEMap, False), 'ExcludeResourceTags': (boolean, True), 'IncludeMap': (IEMap, False), 'PolicyName': (basestring, True), 'Remediati...
props = { 'ACCOUNT': ([basestring], False), }
identifier_body
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera;...
}
{ *blinnKeyPressed = false; }
conditional_block
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera;...
// NOTE: not the same version as in common.rs pub fn processInput(window: &mut glfw::Window, deltaTime: f32, camera: &mut Camera, blinn: &mut bool, blinnKeyPressed: &mut bool) { if window.get_key(Key::Escape) == Action::Press { window.set_should_close(true) } if window.get_key(Key::W) == Action::...
{ let mut blinn = false; let mut blinnKeyPressed = false; let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // tim...
identifier_body
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera;...
while !window.should_close() { // per-frame time logic // -------------------- let currentFrame = glfw.get_time() as f32; deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // events // ----- process_events(&events, &mut firstMouse, &mut ...
let lightPos = vec3(0.0, 0.0, 0.0); // render loop // -----------
random_line_split
_1_advanced_lighting.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::ptr; use std::mem; use std::os::raw::c_void; use std::ffi::CStr; use common::{process_events, loadTexture}; use shader::Shader; use camera::Camera;...
(window: &mut glfw::Window, deltaTime: f32, camera: &mut Camera, blinn: &mut bool, blinnKeyPressed: &mut bool) { if window.get_key(Key::Escape) == Action::Press { window.set_should_close(true) } if window.get_key(Key::W) == Action::Press { camera.ProcessKeyboard(FORWARD, deltaTime); } ...
processInput
identifier_name
rename.py
import os.path import os import random def rename(src, dst): "Atomic rename on windows." # This is taken from mercurial try: os.rename(src, dst) except OSError, err: # If dst exists, rename will fail on windows, and we cannot # unlink an opened file. Instead, the destination is ...
(prefix): for i in range(5): fn = '%s-%08x' % (prefix, random.randint(0, 0xffffffff)) if not os.path.exists(fn): return fn raise IOError, (errno.EEXIST, "No usable temporary filename found") temp = tempname(dst) os.rename(dst, ...
tempname
identifier_name
rename.py
import os.path import os import random def rename(src, dst): "Atomic rename on windows." # This is taken from mercurial try: os.rename(src, dst) except OSError, err:
def tempname(prefix): for i in range(5): fn = '%s-%08x' % (prefix, random.randint(0, 0xffffffff)) if not os.path.exists(fn): return fn raise IOError, (errno.EEXIST, "No usable temporary filename found") temp = tempname(dst) ...
# If dst exists, rename will fail on windows, and we cannot # unlink an opened file. Instead, the destination is moved to # a temporary location if it already exists.
random_line_split
rename.py
import os.path import os import random def rename(src, dst): "Atomic rename on windows." # This is taken from mercurial try: os.rename(src, dst) except OSError, err: # If dst exists, rename will fail on windows, and we cannot # unlink an opened file. Instead, the destination is ...
raise IOError, (errno.EEXIST, "No usable temporary filename found") temp = tempname(dst) os.rename(dst, temp) try: os.unlink(temp) except: # Some rude AV-scanners on Windows may cause the unlink to # fail. Not aborting here just leaks the...
return fn
conditional_block
rename.py
import os.path import os import random def rename(src, dst):
"Atomic rename on windows." # This is taken from mercurial try: os.rename(src, dst) except OSError, err: # If dst exists, rename will fail on windows, and we cannot # unlink an opened file. Instead, the destination is moved to # a temporary location if it already exists. ...
identifier_body
directive.js
import 'velocity-animate'; import 'velocity-animate/velocity.ui'; import templateUrl from './template.html'; import ngModule from '../../module'; class AvLoaderController { constructor($element) { this.av = { $element }; this.active = false; } start()
animate() { const self = this; this.av.$element .find('.loading-bullet') .velocity('transition.slideRightIn', { stagger: 250 }) .velocity({ opacity: 0 }, { delay: 750, duration: 500, complete() { if (self.active) { setTimeout( () => { self.an...
{ this.active = true; this.animate(); }
identifier_body
directive.js
import 'velocity-animate'; import 'velocity-animate/velocity.ui'; import templateUrl from './template.html'; import ngModule from '../../module'; class AvLoaderController { constructor($element) { this.av = { $element }; this.active = false; } start() { this.active = true; this.animate(); ...
controller: AvLoaderController, templateUrl }; }); export default ngModule;
ngModule.directive('avLoader', () => { return { restrict: 'AE', replace: true,
random_line_split
directive.js
import 'velocity-animate'; import 'velocity-animate/velocity.ui'; import templateUrl from './template.html'; import ngModule from '../../module'; class AvLoaderController { constructor($element) { this.av = { $element }; this.active = false; } start() { this.active = true; this.animate(); ...
() { if (self.active) { setTimeout( () => { self.animate() }, 500); } else { self.endAnimation(); } } }); } endAnimation = function() { this.av.$element.find('.loading-bullet').velocity('stop', true); this.av.$element.removeData(); } ...
complete
identifier_name
directive.js
import 'velocity-animate'; import 'velocity-animate/velocity.ui'; import templateUrl from './template.html'; import ngModule from '../../module'; class AvLoaderController { constructor($element) { this.av = { $element }; this.active = false; } start() { this.active = true; this.animate(); ...
} }); } endAnimation = function() { this.av.$element.find('.loading-bullet').velocity('stop', true); this.av.$element.removeData(); } $destroy() { this.active = false; } $postLink() { this.start(); } } ngModule.directive('avLoader', () => { return { restrict: 'AE'...
{ self.endAnimation(); }
conditional_block
conftest.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
trans.rollback() connection.close()
yield session session.close()
random_line_split
conftest.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
(): engine = create_engine('sqlite://', echo=True) Base.metadata.create_all(engine) return engine @pytest.yield_fixture def session(engine): connection = engine.connect() trans = connection.begin() session = Session(bind=connection) yield session session.close() trans.rollback() ...
engine
identifier_name
conftest.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
connection = engine.connect() trans = connection.begin() session = Session(bind=connection) yield session session.close() trans.rollback() connection.close()
identifier_body
pbxareavoip.py
# -*- coding: utf-8 -*- import requests import json from yamlns import namespace as ns from .. import persons class AreaVoip(object): @staticmethod def defaultQueue(): import dbconfig return dbconfig.tomatic.get('areavoip',{}).get('queue', None) def __init__(self): import dbconfi...
(self, queue): response = self._api('INFO', info='agentsconnected', queue = queue, format='json', ) if not response: return [] return [ ns( key = persons.byExtension(extension), extension = extension, na...
queue
identifier_name
pbxareavoip.py
# -*- coding: utf-8 -*- import requests import json from yamlns import namespace as ns from .. import persons class AreaVoip(object): @staticmethod def defaultQueue(): import dbconfig return dbconfig.tomatic.get('areavoip',{}).get('queue', None) def __init__(self): import dbconfi...
def queue(self, queue): response = self._api('INFO', info='agentsconnected', queue = queue, format='json', ) if not response: return [] return [ ns( key = persons.byExtension(extension), extension = extension, ...
self.clear(queue) for name in names: self.add(queue, name)
identifier_body
pbxareavoip.py
# -*- coding: utf-8 -*- import requests import json from yamlns import namespace as ns from .. import persons class AreaVoip(object): @staticmethod def defaultQueue(): import dbconfig return dbconfig.tomatic.get('areavoip',{}).get('queue', None) def __init__(self): import dbconfi...
jsondata=jsondata, format='json', ) def removeExtension(self, extension): self.addExtension(extension,'') def clearExtensions(self): for id, extensionInfo in self._allExtensions(): if not extensionInfo.get('ex_name'): continue ...
object='extension', action='update', objectid=id,
random_line_split
pbxareavoip.py
# -*- coding: utf-8 -*- import requests import json from yamlns import namespace as ns from .. import persons class AreaVoip(object): @staticmethod def defaultQueue(): import dbconfig return dbconfig.tomatic.get('areavoip',{}).get('queue', None) def __init__(self): import dbconfi...
response = self._api('QUEUE', action='add', id = queue, extension = extension, type='NF', # agent type: non-follow ) def clear(self, queue): response = self._api('QUEUE', action='clean', id = queue, ) def stats(self, queue, date=...
return
conditional_block
attention_test.py
# Copyright 2017 Google 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 agreed to in writing,...
def test_layer(self): self._test_layer() class AttentionLayerBahdanauTest(AttentionLayerTest): """Tests the AttentionLayerBahdanau class""" def _create_layer(self): return AttentionLayerBahdanau( params={"num_units": self.attention_dim}, mode=tf.contrib.learn.ModeKeys.TRAIN) def te...
return AttentionLayerDot( params={"num_units": self.attention_dim}, mode=tf.contrib.learn.ModeKeys.TRAIN)
identifier_body
attention_test.py
# Copyright 2017 Google 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 agreed to in writing,...
(self): self._test_layer() if __name__ == "__main__": tf.test.main()
test_layer
identifier_name
attention_test.py
# Copyright 2017 Google 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 agreed to in writing,...
self.seq_len = 10 self.state_dim = 32 def _create_layer(self): """Creates the attention layer. Should be implemented by child classes""" raise NotImplementedError def _test_layer(self): """Tests Attention layer with a given score type""" inputs_pl = tf.placeholder(tf.float32, (None, None,...
random_line_split
attention_test.py
# Copyright 2017 Google 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 agreed to in writing,...
# Scores should sum to 1 scores_sum = np.sum(scores_, axis=1) np.testing.assert_array_almost_equal(scores_sum, np.ones([self.batch_size])) class AttentionLayerDotTest(AttentionLayerTest): """Tests the AttentionLayerDot class""" def _create_layer(self): return AttentionLayerDot( params={...
np.testing.assert_array_equal(batch[idx:], np.zeros_like(batch[idx:]))
conditional_block
gulp-filter.d.ts
// Compiled using typings@0.6.8 // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/1735153b55c4616192219e7edaecdef3971bd5b3/gulp-filter/gulp-filter.d.ts // Type definitions for gulp-filter v3.0.1 // Project: https://github.com/sindresorhus/gulp-filter // Definitions by: Tanguy Krotoff <https:/...
restore?: boolean; passthrough?: boolean; } // A transform stream with a .restore object interface Filter extends NodeJS.ReadWriteStream { restore: NodeJS.ReadWriteStream } } function filter(pattern: string | string[] | filter.FileFunction, options?: filter.Options): filter.Filte...
random_line_split
lightbox.js
// Lightbox ;(function() {
$('.lightboxed').click(function (e) { e.preventDefault(); var image_href = $(this).attr("src"); if ($('#lightbox').length > 0) { $('#content').html('<img src="' + image_href + '" />'); //show lightbox window - you could use .show('fast') for a transition ...
$(document).ready(function () { $('.lightboxed').css('cursor', 'pointer');
random_line_split
lightbox.js
// Lightbox ;(function() { $(document).ready(function () { $('.lightboxed').css('cursor', 'pointer'); $('.lightboxed').click(function (e) { e.preventDefault(); var image_href = $(this).attr("src"); if ($('#lightbox').length > 0)
else { var lightbox = '<div id="lightbox">' + '<p></p>' + '<div id="content">' + //insert clicked link's href into img src '<img src="' + image_href +'" />' + '</div>' + '</div>'; $('body').appen...
{ $('#content').html('<img src="' + image_href + '" />'); //show lightbox window - you could use .show('fast') for a transition $('#lightbox').show(); }
conditional_block
test_core.py
import os import sys import unittest from cStringIO import StringIO from optparse import OptionParser import nose.core from nose.config import Config from nose.tools import set_trace from mock import Bucket, MockOptParser class NullLoader: def loadTestsFromNames(self, names): return unittest.TestSuite() ...
def test_from_zip(self): requested_data = [] # simulates importing nose from a zip archive # with a zipimport.zipimporter instance class fake_zipimporter(object): def get_data(self, path): requested_data.append(path) # Return as str in Py...
usage_txt = nose.core.TestProgram.usage() assert usage_txt.startswith('nose collects tests automatically'), ( "Unexpected usage: '%s...'" % usage_txt[0:50].replace("\n", '\n'))
random_line_split
test_core.py
import os import sys import unittest from cStringIO import StringIO from optparse import OptionParser import nose.core from nose.config import Config from nose.tools import set_trace from mock import Bucket, MockOptParser class NullLoader: def loadTestsFromNames(self, names): return unittest.TestSuite() ...
existing_loader = getattr(nose, '__loader__', Undefined) try: nose.__loader__ = fake_zipimporter() usage_txt = nose.core.TestProgram.usage() self.assertEqual(usage_txt, '<usage>') self.assertEqual(requested_data, [os.path.join( os.path.di...
requested_data.append(path) # Return as str in Python 2, bytes in Python 3. return '<usage>'.encode('utf-8')
identifier_body
test_core.py
import os import sys import unittest from cStringIO import StringIO from optparse import OptionParser import nose.core from nose.config import Config from nose.tools import set_trace from mock import Bucket, MockOptParser class NullLoader: def loadTestsFromNames(self, names): return unittest.TestSuite() ...
(object): def get_data(self, path): requested_data.append(path) # Return as str in Python 2, bytes in Python 3. return '<usage>'.encode('utf-8') existing_loader = getattr(nose, '__loader__', Undefined) try: nose.__loader__ = fake_...
fake_zipimporter
identifier_name
test_core.py
import os import sys import unittest from cStringIO import StringIO from optparse import OptionParser import nose.core from nose.config import Config from nose.tools import set_trace from mock import Bucket, MockOptParser class NullLoader: def loadTestsFromNames(self, names): return unittest.TestSuite() ...
if __name__ == '__main__': unittest.main()
del nose.__loader__
conditional_block
unpin_chat_message.rs
use crate::requests::*; use crate::types::*; ///Use this method to unpin a message in a supergroup or a channel. /// The bot must be an administrator in the chat for this to work /// and must have the ‘can_pin_messages’ admin right in the /// supergroup or ‘can_edit_messages’ admin right in the channel. #[derive(Debug...
hat_id: ChatRef, } impl Request for UnpinChatMessage { type Type = JsonRequestType<Self>; type Response = JsonTrueToUnitResponse; fn serialize(&self) -> Result<HttpRequest, Error> { Self::Type::serialize(RequestUrl::method("unpinChatMessage"), self) } } impl UnpinChatMessage { fn new<C>(c...
tMessage { c
identifier_name
unpin_chat_message.rs
use crate::requests::*; use crate::types::*; ///Use this method to unpin a message in a supergroup or a channel. /// The bot must be an administrator in the chat for this to work /// and must have the ‘can_pin_messages’ admin right in the /// supergroup or ‘can_edit_messages’ admin right in the channel. #[derive(Debug...
}
}
random_line_split
utils.py
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the...
def to_bytes(string): """ Converts the given string into bytes """ if type(string) is bytes: return string return bytes(string, "UTF-8") def from_bytes(data): """ Converts the given bytes into a string """ if type(data) is str...
float )
random_line_split
utils.py
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the...
# ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """ ...
""" Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8")
identifier_body
utils.py
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the...
return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """ Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is...
return data
conditional_block
utils.py
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Utility methods, for compatibility between Python version :author: Thomas Calmant :copyright: Copyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the...
(data): """ Converts the given bytes into a string """ if type(data) is str: return data return str(data, "UTF-8") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """...
from_bytes
identifier_name
setup.py
from setuptools import setup, find_packages import imp version = imp.load_source('crema.version', 'crema/version.py') setup( name='crema', version=version.version, description="Convolutional-recurrent estimators for music analysis", author='Brian McFee', url='http://github.com/bmcfee/crema', ...
"Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", ], keywords='audio music learning', license='ISC', install_requires=['six', 'librosa>=0.6', 'jams>=0.3', 'scikit-learn>=0.18', ...
"Topic :: Software Development", "Programming Language :: Python :: 3",
random_line_split
confirmation.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2013-2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the who...
sale_order_obj = self.pool['sale.order'] result = super(sale_order_confirm, self).sale_order_confirmated(cr, uid, ids, context=context) sale_order_confirm_data = self.browse(cr, uid, ids[0], context=context) if result.get('res_id'): sale_order_obj.write(cr, uid, result['res_id'], { ...
identifier_body
confirmation.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2013-2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the who...
return result
picking_obj = self.pool['stock.picking'] picking_ids = picking_obj.search(cr, uid, [('sale_id', '=', order.id)], context=context) for picking_id in picking_ids: picking_obj.write(cr, uid, picking_id, { 'cig': sale_order_confirm_data.cig or '', ...
conditional_block
confirmation.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2013-2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the who...
(orm.TransientModel): _inherit = "sale.order.confirm" _columns = { 'cig': fields.char('CIG', size=64, help="Codice identificativo di gara"), 'cup': fields.char('CUP', size=64, help="Codice unico di Progetto") } # def default_get(self, cr, uid, fields, context=None): # sale_...
sale_order_confirm
identifier_name
confirmation.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2013-2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the who...
class sale_order_confirm(orm.TransientModel): _inherit = "sale.order.confirm" _columns = { 'cig': fields.char('CIG', size=64, help="Codice identificativo di gara"), 'cup': fields.char('CUP', size=64, help="Codice unico di Progetto") } # def default_get(self, cr, uid, fields, cont...
import decimal_precision as dp import netsvc from tools import ustr
random_line_split
15.2.3.6-3-3.js
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or ot...
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met:
random_line_split
15.2.3.6-3-3.js
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// ...
} }, precondition: function prereq() { return fnExists(Object.defineProperty); } });
{ return true; }
conditional_block