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
baseurl.py
""" html page utils """
from scrapely.htmlpage import parse_html, HtmlTagType ABSURLRE = re.compile("^https?\:\/\/") DOCTYPERE = re.compile("<!DOCTYPE.*?>", re.S | re.I) def _is_abs_url(url): return bool(ABSURLRE.match(url)) def insert_base_url(html, base): """ Inserts the given base url if does not exist in html source, or...
import urlparse, re
random_line_split
baseurl.py
""" html page utils """ import urlparse, re from scrapely.htmlpage import parse_html, HtmlTagType ABSURLRE = re.compile("^https?\:\/\/") DOCTYPERE = re.compile("<!DOCTYPE.*?>", re.S | re.I) def
(url): return bool(ABSURLRE.match(url)) def insert_base_url(html, base): """ Inserts the given base url if does not exist in html source, or replace the existing if needed """ baseurl = baseelement = headelement = htmlelement = None for element in parse_html(html): if getattr(elemen...
_is_abs_url
identifier_name
inventory.ts
/// /// Copyright 2015 Red Hat, Inc. and/or its affiliates /// and other contributors as indicated by the @author tags. /// /// 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...
}
random_line_split
inventory.ts
/// /// Copyright 2015 Red Hat, Inc. and/or its affiliates /// and other contributors as indicated by the @author tags. /// /// 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...
}; $scope.closeChart = function() { delete $rootScope.metricData; }; }]); }
{ hkMetric.NumericMetricData.get({tenantId: _tenantId, numericId: _metricId, buckets: 60}, function (data) { $rootScope.metricData = data; }); }
conditional_block
crypto.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CryptoBinding; use dom::bindings::codeg...
(input: *mut JSObject) -> bool { match unsafe { JS_GetArrayBufferViewType(input) } { Type::Uint8 | Type::Uint8Clamped | Type::Int8 | Type::Uint16 | Type::Int16 | Type::Uint32 | Type::Int32 => true, _ => false } }
is_integer_buffer
identifier_name
crypto.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CryptoBinding; use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindin...
random_line_split
crypto.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CryptoBinding; use dom::bindings::codeg...
if !is_integer_buffer(input) { return Err(Error::TypeMismatch); } if length > 65536 { return Err(Error::QuotaExceeded); } let mut buffer = unsafe { slice::from_raw_parts_mut(data, length as usize) }; self.rng.borrow_mut().fil...
{ return Err(Error::Type("Argument to Crypto.getRandomValues is not an ArrayBufferView".to_owned())); }
conditional_block
15.9.5.23-1.js
/* The contents of this file are subject to the Netscape Public License * Version 1.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.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS IS" *...
(t) { t = LocalTime(t); return ( MyDateFromTime(t) ); } function UTCDateFromTime(t) { return ( MyDateFromTime(t) ); } function MyDateFromTime( t ) { var d = new MyDate(); d.year = YearFromTime(t); d.month = MonthFromTime(t); d.date = DateFromTime(t); d.hours = HourFr...
LocalDateFromTime
identifier_name
15.9.5.23-1.js
/* The contents of this file are subject to the Netscape Public License * Version 1.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.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS IS" *...
{ for ( tc=0; tc < testcases.length; tc++ ) { testcases[tc].passed = writeTestCaseResult( testcases[tc].expect, testcases[tc].actual, testcases[tc].description +" = "+ testcases[tc].actual ); ...
identifier_body
15.9.5.23-1.js
/* The contents of this file are subject to the Netscape Public License * Version 1.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.mozilla.org/NPL/
* under the License. * * The Original Code is Mozilla Communicator client code, released March * 31, 1998. * * The Initial Developer of the Original Code is Netscape Communications * Corporation. Portions created by Netscape are Copyright (C) 1998 * Netscape Communications Corporation. All Rights Reserved. *...
* * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations
random_line_split
15.9.5.23-1.js
/* The contents of this file are subject to the Netscape Public License * Version 1.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.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS IS" *...
DateCase.setTime( setTime ); var DateString = "var d = new Date("+startTime+"); d.setTime("+setTime+"); d" ; var UTCDate = UTCDateFromTime ( Number(setTime) ); var LocalDate = LocalDateFromTime( Number(setTime) ); var item = testcases.length; // fixed_year = ( ExpectDate.year >=1900 || Expec...
{ DateCase = new Date( startTime ); }
conditional_block
new-character.tsx
import * as React from 'react' import { MarkEditor } from '../mark-editor' import { ImageSelect } from '../image-select' import { ImageThumb } from '../image-thumb' import { SaveButton } from '../save-button' import { FormInput } from '../form-utils' import { RawDraft } from '../raw-draft' import { API, APIError, Char...
} private static _makeSlug(str: string|undefined) { return str ? str.toLowerCase().replace(/[^a-z0-9]/g, ' ').replace(/ +/g, ' ').trim().replace(/ /g, '-') : undefined } private _handleChange<P extends keyof(CharacterInput)>(key: P, value: CharacterInput[P]) { this.setState({c...
{ const saving = api.saveCharacter(this.state.char) .then(char => { document.location.href = `/chars/c/${char.slug}` }).catch(err => { this.setState({saving: undefined}) if (err instanceof APIError && err.errors) ...
conditional_block
new-character.tsx
import * as React from 'react' import { MarkEditor } from '../mark-editor' import { ImageSelect } from '../image-select' import { ImageThumb } from '../image-thumb' import { SaveButton } from '../save-button' import { FormInput } from '../form-utils' import { RawDraft } from '../raw-draft' import { API, APIError, Char...
<select className='form-control' disabled={!!this.state.saving} value={this.state.char.visible?'visible':''} onChange={ev => this._handleChange('visible', ev.target.value === 'visible')}> <option value='visible'>Party Public</option> ...
random_line_split
new-character.tsx
import * as React from 'react' import { MarkEditor } from '../mark-editor' import { ImageSelect } from '../image-select' import { ImageThumb } from '../image-thumb' import { SaveButton } from '../save-button' import { FormInput } from '../form-utils' import { RawDraft } from '../raw-draft' import { API, APIError, Char...
(api: API) { if (!this.state.saving) { const saving = api.saveCharacter(this.state.char) .then(char => { document.location.href = `/chars/c/${char.slug}` }).catch(err => { this.setState({saving: undefined}) ...
_handleSubmitClicked
identifier_name
new-character.tsx
import * as React from 'react' import { MarkEditor } from '../mark-editor' import { ImageSelect } from '../image-select' import { ImageThumb } from '../image-thumb' import { SaveButton } from '../save-button' import { FormInput } from '../form-utils' import { RawDraft } from '../raw-draft' import { API, APIError, Char...
private _handleChange<P extends keyof(CharacterInput)>(key: P, value: CharacterInput[P]) { this.setState({char: {...this.state.char, [key]: value}}) } public render() { const current = this.state.char return ( <div> <div className='form-row'> ...
{ return str ? str.toLowerCase().replace(/[^a-z0-9]/g, ' ').replace(/ +/g, ' ').trim().replace(/ /g, '-') : undefined }
identifier_body
spinner.py
import sys import time from threading import Thread class Spinner(Thread): #Set the screen position of the spinner (chars from the left). spin_screen_pos = 1 #Set the current index position in the spinner character list. char_index_pos = 0 #Set the time between character changes in the spinner. ...
elif type == 1: self.char = ['.', 'o', 'O', 'o', '.'] elif type == 2: self.char = ['|', '/', '-', '\\', '-'] else: self.char = ['*', '#', '@', '%', '+'] self.len = len(self.char) def Print(self, crnt): str, crnt = self.curr(crnt) ...
self.char = ['O', 'o', '-', 'o', '0']
conditional_block
spinner.py
import sys import time from threading import Thread class Spinner(Thread): #Set the screen position of the spinner (chars from the left). spin_screen_pos = 1 #Set the current index position in the spinner character list. char_index_pos = 0 #Set the time between character changes in the spinner. ...
(self, crnt): str, crnt = self.curr(crnt) sys.stdout.write("\b \b%s" % str) sys.stdout.flush() # Flush stdout to get output before sleeping! time.sleep(self.sleep_time) return crnt def curr(self, crnt): """ Iterator for the character list position ""...
Print
identifier_name
spinner.py
import sys import time from threading import Thread class Spinner(Thread): #Set the screen position of the spinner (chars from the left).
#Set the spinner type: 0-3 spin_type = 2 def __init__(self, type=spin_type): Thread.__init__(self) self.setDaemon(True) self.stop_spinner = False self.stopped = False if type == 0: self.char = ['O', 'o', '-', 'o', '0'] elif type == 1: ...
spin_screen_pos = 1 #Set the current index position in the spinner character list. char_index_pos = 0 #Set the time between character changes in the spinner. sleep_time = 1
random_line_split
spinner.py
import sys import time from threading import Thread class Spinner(Thread): #Set the screen position of the spinner (chars from the left).
self.char = ['*', '#', '@', '%', '+'] self.len = len(self.char) def Print(self, crnt): str, crnt = self.curr(crnt) sys.stdout.write("\b \b%s" % str) sys.stdout.flush() # Flush stdout to get output before sleeping! time.sleep(self.sleep_time) return crnt ...
spin_screen_pos = 1 #Set the current index position in the spinner character list. char_index_pos = 0 #Set the time between character changes in the spinner. sleep_time = 1 #Set the spinner type: 0-3 spin_type = 2 def __init__(self, type=spin_type): Thread.__init__(self) sel...
identifier_body
NewUsersDefinition.js
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue inste...
} /** * * @member {Array.<module:model/UserInformation>} newUsers */ exports.prototype['newUsers'] = undefined; return exports; }));
if (data.hasOwnProperty('newUsers')) { obj['newUsers'] = ApiClient.convertToType(data['newUsers'], [UserInformation]); } } return obj;
random_line_split
Mouse.js
/* --- name: Mouse description: Maps mouse events to their touch counterparts authors: Christoph Pojer (@cpojer)
provides: Mouse ... */ if (!Browser.Features.Touch) (function(){ var down = false; var condition = function(event, type){ if (type == 'touchstart') down = true; else if (type == 'touchend') down = false; else if (type == 'touchmove' && !down) return false; event.targetTouches = []; event.changedTouches = event...
license: MIT-style license. requires: [Custom-Event/Element.defineCustomEvent, Browser.Features.Touch]
random_line_split
Post.ts
import {Entity} from "../../../../../../src/decorator/entity/Entity"; import {PrimaryGeneratedColumn} from "../../../../../../src/decorator/columns/PrimaryGeneratedColumn"; import {Column} from "../../../../../../src/decorator/columns/Column"; @Entity() export class Post { @PrimaryGeneratedColumn() id: number...
length: 50 }) varying_character: string; @Column("nchar", { length: 50 }) nchar: string; @Column("native character", { length: 50 }) native_character: string; @Column("nvarchar", { length: 50 }) nvarchar: string; }
@Column("varying character", {
random_line_split
Post.ts
import {Entity} from "../../../../../../src/decorator/entity/Entity"; import {PrimaryGeneratedColumn} from "../../../../../../src/decorator/columns/PrimaryGeneratedColumn"; import {Column} from "../../../../../../src/decorator/columns/Column"; @Entity() export class
{ @PrimaryGeneratedColumn() id: number; @Column("character", { length: 50 }) character: string; @Column("varchar", { length: 50 }) varchar: string; @Column("varying character", { length: 50 }) varying_character: string; @Column("nchar", { ...
Post
identifier_name
test_playbookrunner.py
# -*- coding: utf-8 -*- # Copyright (C) 2016 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
# GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with edi. If not, see <http://www.gnu.org/licenses/>. from edi.lib.configurationparser import ConfigurationParser from edi.lib.playbookrunner import PlaybookRunner from tests.libt...
# # edi 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
random_line_split
test_playbookrunner.py
# -*- coding: utf-8 -*- # Copyright (C) 2016 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
def verify_extra_vars(file): print(file) with open(file, encoding='utf-8') as f: extra_vars = yaml.load(f) assert extra_vars['edi_config_management_user_name'] == 'edicfgmgmt' mountpoints = extra_vars['edi_shared_folder_mountpoints'] assert len(mountpoints) == 2 assert...
with open(file, encoding='utf-8') as f: assert 'fake-container' in f.read()
identifier_body
test_playbookrunner.py
# -*- coding: utf-8 -*- # Copyright (C) 2016 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
monkeypatch.setattr(mockablerun, 'run_mockable', fake_ansible_playbook_run) def fakechown(*_): pass monkeypatch.setattr(shutil, 'chown', fakechown) with open(config_files, "r") as main_file: parser = ConfigurationParser(main_file) runner = PlaybookRunner(parser, "fake-contai...
return subprocess.run(*popenargs, **kwargs)
conditional_block
test_playbookrunner.py
# -*- coding: utf-8 -*- # Copyright (C) 2016 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
(config_files, monkeypatch): def fake_ansible_playbook_run(*popenargs, **kwargs): command = popenargs[0] if command[0] == 'ansible-playbook': assert 'lxd' == get_command_parameter(command, '--connection') verify_inventory(get_command_parameter(command, '--inventory')) ...
test_lxd_connection
identifier_name
timer.rs
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Timers for non-Linux/non-Windows OSes //! //! This module implements timers with a worker thread, select(), and a lot of //! witchcraft that turns ou...
(active: &mut Vec<Box<Inner>>, dead: &mut Vec<(uint, Box<Inner>)>) { if active.is_empty() { return } let mut timer = active.remove(0); let mut cb = timer.cb.take().unwrap(); cb.call(); if timer.repeat { timer.cb = Some(cb); timer.target += t...
signal
identifier_name
timer.rs
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Timers for non-Linux/non-Windows OSes //! //! This module implements timers with a worker thread, select(), and a lot of //! witchcraft that turns ou...
} } pub fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>) { let now = now(); let mut inner = self.inner(); inner.repeat = false; inner.cb = Some(cb); inner.interval = msecs; inner.target = now + msecs
{ panic!("failed to sleep, but not because of EINTR?"); }
conditional_block
timer.rs
license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Timers for non-Linux/non-Windows OSes //! //! This module implements timers with a worker thread, select(), and a lot of //! witchcraft that ...
let mut to_sleep = libc::timespec { tv_sec: (ms / 1000) as libc::time_t, tv_nsec: ((ms % 1000) * 1000000) as libc::c_long, }; while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 { if os::errno() as int != libc::EINTR as int { panic!...
pub fn sleep(&mut self, ms: u64) { let mut inner = self.inner(); inner.cb = None; // cancel any previous request self.inner = Some(inner);
random_line_split
lib.rs
pub mod network_event; } mod protocol; #[derive(RustcEncodable)] struct ConsoleAPICall { from: String, __type__: String, message: ConsoleMsg, } #[derive(RustcEncodable)] struct ConsoleMsg { level: String, timeStamp: u64, arguments: Vec<String>, filename: String, lineNumber: u32, c...
{ //TODO: Delete from map like Firefox does? name.into_mut().clone() }
conditional_block
lib.rs
::{ConsoleMessage, DevtoolsControlMsg, NetworkEvent}; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; use msg::constellation_msg::{PipelineId, WorkerId}; use util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry...
// We need separate actor representations for each script global that exists; // clients can theoretically connect to multiple globals simultaneously. // TODO: move this into the root or tab modules? fn handle_new_global(actors: Arc<Mutex<ActorRegistry>>, ids: (PipelineId, Opt...
{ let actors = actors.lock().unwrap(); let framerate_actor = actors.find::<FramerateActor>(&actor_name); framerate_actor.add_tick(tick); }
identifier_body
lib.rs
_traits::{ConsoleMessage, DevtoolsControlMsg, NetworkEvent}; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; use msg::constellation_msg::{PipelineId, WorkerId}; use util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map...
ConsoleMessage::LogMessage { message, filename, lineNumber, columnNumber, } => { let msg = ConsoleAPICall { from: console_actor.name.clone(), __type__: "consoleAPICall".to_stri...
let console_actor_name = find_console_actor(actors.clone(), id, actor_pipelines); let actors = actors.lock().unwrap(); let console_actor = actors.find::<ConsoleActor>(&console_actor_name); match console_message {
random_line_split
lib.rs
::{ConsoleMessage, DevtoolsControlMsg, NetworkEvent}; use devtools_traits::{DevtoolsPageInfo, DevtoolScriptControlMsg}; use msg::constellation_msg::{PipelineId, WorkerId}; use util::task::spawn_named; use std::borrow::ToOwned; use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry...
(actors: Arc<Mutex<ActorRegistry>>, actor_name: String, tick: f64) { let actors = actors.lock().unwrap(); let framerate_actor = actors.find::<FramerateActor>(&actor_name); framerate_actor.add_tick(tick); } // We need separate actor representations for each script global that exists; ...
handle_framerate_tick
identifier_name
documentfragment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentFragmentBinding; use dom::bindings::codegen::Bindings::DocumentFragm...
}
{ let root: JSRef<Node> = NodeCast::from_ref(self); root.query_selector_all(selectors) }
identifier_body
documentfragment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::InheritTypes::DocumentFragmentDerived; use dom::bindings::codegen::InheritTypes::{ElementCast, NodeCast}; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::js::{JSRef, Rootable, Temporary}; use dom::bi...
* License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentFragmentBinding; use dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods;
random_line_split
documentfragment.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::DocumentFragmentBinding; use dom::bindings::codegen::Bindings::DocumentFragm...
(self) -> Temporary<HTMLCollection> { let window = window_from_node(self).root(); HTMLCollection::children(window.r(), NodeCast::from_ref(self)) } // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild fn GetFirstElementChild(self) -> Option<Temporary<Element>> { NodeCast:...
Children
identifier_name
sensors_raw_left.py
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) TRIG = 35 ECHO = 38 GPIO.setup(TRIG,GPIO.OUT) GPIO.output(TRIG,0) GPIO.setup(ECHO,GPIO.IN) time.sleep(0.1) print ("Starting gesture recognition") try: # here you put your main loop or block of code while True: value_list = [] for x in xran...
value_list.sort(); print value_list[2] except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C print ("exiting") except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging ...
distance = (stop - start) * 17000 value_list.append(distance) time.sleep(0.025)
random_line_split
sensors_raw_left.py
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) TRIG = 35 ECHO = 38 GPIO.setup(TRIG,GPIO.OUT) GPIO.output(TRIG,0) GPIO.setup(ECHO,GPIO.IN) time.sleep(0.1) print ("Starting gesture recognition") try: # here you put your main loop or block of code while True:
print value_list[2] except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C print ("exiting") except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging # so only use it...
value_list = [] for x in xrange(0,5): GPIO.output(TRIG,1) time.sleep(0.0001) GPIO.output(TRIG,0) start = time.time() while GPIO.input(ECHO) == 0 and time.time()-start < 0.4: pass start = time.time() while GPIO.input(ECHO) == 1: pass stop = time.time() distance = (stop - ...
conditional_block
base.py
import typing import anyio from starlette.requests import Request from starlette.responses import Response, StreamingResponse from starlette.types import ASGIApp, Receive, Scope, Send RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] DispatchFunction = typing.Callable[ [Request, Re...
raise app_exc raise RuntimeError("No response returned.") assert message["type"] == "http.response.start" async def body_stream() -> typing.AsyncGenerator[bytes, None]: async with recv_stream: async for message in recv_str...
try: message = await recv_stream.receive() except anyio.EndOfStream: if app_exc is not None:
random_line_split
base.py
import typing import anyio from starlette.requests import Request from starlette.responses import Response, StreamingResponse from starlette.types import ASGIApp, Receive, Scope, Send RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] DispatchFunction = typing.Callable[ [Request, Re...
() -> None: nonlocal app_exc async with send_stream: try: await self.app(scope, request.receive, send_stream.send) except Exception as exc: app_exc = exc task_group.start_soon(coro) ...
coro
identifier_name
base.py
import typing import anyio from starlette.requests import Request from starlette.responses import Response, StreamingResponse from starlette.types import ASGIApp, Receive, Scope, Send RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] DispatchFunction = typing.Callable[ [Request, Re...
task_group.start_soon(coro) try: message = await recv_stream.receive() except anyio.EndOfStream: if app_exc is not None: raise app_exc raise RuntimeError("No response returned.") assert message["type"...
nonlocal app_exc async with send_stream: try: await self.app(scope, request.receive, send_stream.send) except Exception as exc: app_exc = exc
identifier_body
base.py
import typing import anyio from starlette.requests import Request from starlette.responses import Response, StreamingResponse from starlette.types import ASGIApp, Receive, Scope, Send RequestResponseEndpoint = typing.Callable[[Request], typing.Awaitable[Response]] DispatchFunction = typing.Callable[ [Request, Re...
response = StreamingResponse( status_code=message["status"], content=body_stream() ) response.raw_headers = message["headers"] return response async with anyio.create_task_group() as task_group: request = Request(scope, receive=recei...
raise app_exc
conditional_block
buttons.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * 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, ...
{ Decrement, Increment, Quit, } // Create the structure that holds the widgets used in the view. #[derive(Clone)] struct Widgets { counter_label: Label, minus_button: Button, plus_button: Button, window: Window, } struct Win { model: Model, widgets: Widgets, } impl Update for Win...
Msg
identifier_name
buttons.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * 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, ...
use gtk::{ Button, Inhibit, Label, Window, WindowType, prelude::ButtonExt, prelude::ContainerExt, prelude::LabelExt, prelude::WidgetExt, }; use gtk::Orientation::Vertical; use relm_derive::Msg; use relm::{connect, Relm, Update, Widget, WidgetTest}; struct Model { counter: i32, }...
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
random_line_split
helper.js
var path = require("path"); var utils = require("utils-pkg"); /** * Parse options of the package * * @param {Object} opts Options given from the server * @return {Object} Options object merged with default */ module.exports.parseOptions = function(opts){ if(typeof opts == "undefined"){ throw new Erro...
if(val == true){ return "index" } else{ return null; } } else if(utils.isString(val)){ return val; } else{ throw new Error("Index value not valid"); } } /** * Compares 2 date times regardless of which format they are, * ignoring milliseconds * * @param {Date} time1 The date string/obje...
* @param {String|Boolean} val The provided value for the index * @return {String|Null} Return the correct value for file handler */ module.exports.resolveIndex = function(val){ if(utils.isBoolean(val)){
random_line_split
helper.js
var path = require("path"); var utils = require("utils-pkg"); /** * Parse options of the package * * @param {Object} opts Options given from the server * @return {Object} Options object merged with default */ module.exports.parseOptions = function(opts){ if(typeof opts == "undefined"){ throw new Erro...
return dir; } /** * Resolve the index value defined in options * Either boolean or string value * * @param {String|Boolean} val The provided value for the index * @return {String|Null} Return the correct value for file handler */ module.exports.resolveIndex = function(val){ if(utils.isBoolean(val)){ ...
{ if(path.extname(dir)){ return dir.replace(path.extname(dir), "." + ext); } return dir + "." + ext; }
conditional_block
sitemap.py
# -*- coding: utf-8 -*- """ Sitemap builder """ import json, os
from treelib import Tree from optimus.conf import settings class SitemapError(Exception): pass class PageSitemap(object): """ Construct ressource page to build and published sitemap """ def __init__(self, tree, view, with_root=False): self.tree = json.loads(tree.to_json(with_data=True)...
random_line_split
sitemap.py
# -*- coding: utf-8 -*- """ Sitemap builder """ import json, os from treelib import Tree from optimus.conf import settings class SitemapError(Exception): pass class PageSitemap(object): """ Construct ressource page to build and published sitemap """ def __init__(self, tree, view, with_root=Fal...
def get_public_sitemap(self, tree): """ Return a list of sitemap nodes If 'PageSitemap.with_root' is False, return only root children nodes, else return the full dict containing root node. """ if not self.with_root: return tree['root']['children'] ...
self.tree = json.loads(tree.to_json(with_data=True)) self.view = view self.with_root = with_root # For public sitemap # Public sitemap self.sitemap = self.get_public_sitemap(self.tree) # Store a flat list of every ressources to build as pages self.ressources = self.recu...
identifier_body
sitemap.py
# -*- coding: utf-8 -*- """ Sitemap builder """ import json, os from treelib import Tree from optimus.conf import settings class SitemapError(Exception): pass class PageSitemap(object): """ Construct ressource page to build and published sitemap """ def __init__(self, tree, view, with_root=Fal...
(self, children, pages=[]): """ Return a flat ressources list from given children """ for branch in children: for leaf_name, leaf_content in branch.items(): datas = leaf_content['data'] pages.append(self.view( title=leaf_nam...
recursive_ressources
identifier_name
sitemap.py
# -*- coding: utf-8 -*- """ Sitemap builder """ import json, os from treelib import Tree from optimus.conf import settings class SitemapError(Exception): pass class PageSitemap(object): """ Construct ressource page to build and published sitemap """ def __init__(self, tree, view, with_root=Fal...
for root, dirs, files in os.walk(scanned_path): # Current relative dir from demos dir relative_dir = os.path.relpath(root, base_path) if not relative_dir.startswith('_'): if relative_dir == '.': parent = None current_dir = "root" ...
base_path = scanned_path
conditional_block
index.d.ts
// Type definitions for React Router 4.0 // Project: https://github.com/ReactTraining/react-router // Definitions by: Sergey Buturlakin <https://github.com/sergey-buturlakin> // Yuichi Murata <https://github.com/mrk21> // Václav Ostrožlík <https://github.com/vasek17> // ...
// TypeScript Version: 2.2 import * as React from 'react'; import * as H from 'history'; // This is the type of the context object that will be passed down to all children of // a `Router` component: export interface RouterChildContext<P> { router: { history: H.History route: { location: H....
// Tanguy Krotoff <https://github.com/tkrotoff> // Huy Nguyen <https://github.com/huy-nguyen> // Jérémy Fauvel <https://github.com/grmiade> // Daniel Roth <https://github.com/DaIgeb> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
random_line_split
index.d.ts
// Type definitions for React Router 4.0 // Project: https://github.com/ReactTraining/react-router // Definitions by: Sergey Buturlakin <https://github.com/sergey-buturlakin> // Yuichi Murata <https://github.com/mrk21> // Václav Ostrožlík <https://github.com/vasek17> // ...
nds React.Component<RouteProps, {}> { } export interface RouterProps { history: any; } export class Router extends React.Component<RouterProps, {}> { } export interface StaticRouterProps { basename?: string; location?: string | object; context?: object; } export class StaticRouter extends React....
exte
identifier_name
clouds.js
function
() { function webGlSupport() { try { return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('experimental-webgl'); } catch(e) { return false; } } this.start = function() { container = document.createElement('div'); $('body').prepend(container); ...
Clouds
identifier_name
clouds.js
function Clouds() { function webGlSupport() { try { return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('experimental-webgl'); } catch(e) { return false; } } this.start = function() { container = document.createElement('div'); $('body').prepend(c...
type: "f", value: fog.near }, "fogFar": { type: "f", value: fog.far }, }, vertexShader: 'varying vec2 vUv; void main() {vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);}', ...
{ camera = new THREE.PerspectiveCamera(30, window.innerWidth / (window.innerHeight + 3), 1, 3000); camera.position.z = 6000; scene = new THREE.Scene(); geometry = new THREE.Geometry(); var texture = THREE.ImageUtils.loadTexture('/img/cloud10.png', null, animate); texture....
identifier_body
clouds.js
function Clouds() { function webGlSupport() { try { return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('experimental-webgl'); } catch(e) { return false; } } this.start = function() { container = document.createElement('div'); $('body').prepend(c...
type: "f", value: fog.near }, "fogFar": { type: "f", value: fog.far }, }, vertexShader: 'varying vec2 vUv; void main() {vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);}', ...
value: fog.color }, "fogNear": {
random_line_split
clouds.js
function Clouds() { function webGlSupport() { try { return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('experimental-webgl'); } catch(e) { return false; } } this.start = function() { container = document.createElement('div'); $('body').prepend(c...
mesh = new THREE.Mesh(geometry, material); scene.add(mesh); mesh = new THREE.Mesh(geometry, material); mesh.position.z = -8000; scene.add(mesh); renderer = new THREE.WebGLRenderer({ antialias: false }); renderer.setSize(window.innerWidth, (windo...
{ plane.position.x = Math.random() * 1000 - 500; plane.position.y = -Math.random() * Math.random() * 200 - 15; plane.position.z = i; plane.rotation.z = Math.random() * Math.PI; plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5; THREE.Ge...
conditional_block
divsum_analysis.py
#!/usr/bin/python import sys print "divsum_analysis.py DivsumFile NumberOfNucleotides" try: file = sys.argv[1] except: file = raw_input("Introduce RepeatMasker's Divsum file: ") try: nucs = sys.argv[2] except: nucs = raw_input("Introduce number of analysed nucleotides: ") nucs = int(nucs) data = o...
abs = open(file+".abs", "w") rel = open(file+".rel", "w") for n in range(0,n_el): abs.write("%s\t%s\n" % (matrix[n][0], sum(matrix[n][1]))) rel.write("%s\t%s\n" % (matrix[n][0], round(1.0*sum(matrix[n][1])/nucs,100)))
info = line.split() info = info[1:] for n in range(0,n_el): matrix[n][1].append(int(info[n]))
conditional_block
divsum_analysis.py
#!/usr/bin/python import sys print "divsum_analysis.py DivsumFile NumberOfNucleotides" try: file = sys.argv[1] except: file = raw_input("Introduce RepeatMasker's Divsum file: ") try: nucs = sys.argv[2] except: nucs = raw_input("Introduce number of analysed nucleotides: ") nucs = int(nucs) data = o...
matrix[n][1].append(int(info[n])) abs = open(file+".abs", "w") rel = open(file+".rel", "w") for n in range(0,n_el): abs.write("%s\t%s\n" % (matrix[n][0], sum(matrix[n][1]))) rel.write("%s\t%s\n" % (matrix[n][0], round(1.0*sum(matrix[n][1])/nucs,100)))
info = info[1:] for n in range(0,n_el):
random_line_split
test_prepared_report.py
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies and Contributors # License: MIT. See LICENSE import frappe import unittest import json class TestPreparedReport(unittest.TestCase): def setUp(self): self.report = frappe.get_doc({ "doctype": "Report", "name": "Permitted Documents For User" }...
self.assertTrue('QUEUED' == self.prepared_report_doc.status.upper()) self.assertTrue(self.prepared_report_doc.report_start_time)
def test_for_creation(self):
random_line_split
test_prepared_report.py
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies and Contributors # License: MIT. See LICENSE import frappe import unittest import json class TestPreparedReport(unittest.TestCase): def
(self): self.report = frappe.get_doc({ "doctype": "Report", "name": "Permitted Documents For User" }) self.filters = { "user": "Administrator", "doctype": "Role" } self.prepared_report_doc = frappe.get_doc({ "doctype": "Prepared Report", "report_name": self.report.name, "filters": json.du...
setUp
identifier_name
test_prepared_report.py
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies and Contributors # License: MIT. See LICENSE import frappe import unittest import json class TestPreparedReport(unittest.TestCase): def setUp(self):
def tearDown(self): frappe.set_user("Administrator") self.prepared_report_doc.delete() def test_for_creation(self): self.assertTrue('QUEUED' == self.prepared_report_doc.status.upper()) self.assertTrue(self.prepared_report_doc.report_start_time)
self.report = frappe.get_doc({ "doctype": "Report", "name": "Permitted Documents For User" }) self.filters = { "user": "Administrator", "doctype": "Role" } self.prepared_report_doc = frappe.get_doc({ "doctype": "Prepared Report", "report_name": self.report.name, "filters": json.dumps(self.f...
identifier_body
admin.py
""" Django Admin pages for DiscountRestrictionConfig. """ from django.contrib import admin from django.utils.translation import gettext_lazy as _ from openedx.core.djangoapps.config_model_utils.admin import StackedConfigModelAdmin from .models import DiscountPercentageConfig, DiscountRestrictionConfig class Disco...
(StackedConfigModelAdmin): """ Admin to configure discount percentage """ fieldsets = ( ('Context', { 'fields': DiscountRestrictionConfig.KEY_FIELDS, 'description': _( 'These define the context to configure the percentage for the first purchase discount.' ...
DiscountPercentageConfigAdmin
identifier_name
admin.py
""" Django Admin pages for DiscountRestrictionConfig. """ from django.contrib import admin from django.utils.translation import gettext_lazy as _ from openedx.core.djangoapps.config_model_utils.admin import StackedConfigModelAdmin from .models import DiscountPercentageConfig, DiscountRestrictionConfig class Disco...
admin.site.register(DiscountPercentageConfig, DiscountPercentageConfigAdmin)
""" Admin to configure discount percentage """ fieldsets = ( ('Context', { 'fields': DiscountRestrictionConfig.KEY_FIELDS, 'description': _( 'These define the context to configure the percentage for the first purchase discount.' 'If multiple co...
identifier_body
admin.py
""" Django Admin pages for DiscountRestrictionConfig. """ from django.contrib import admin from django.utils.translation import gettext_lazy as _ from openedx.core.djangoapps.config_model_utils.admin import StackedConfigModelAdmin from .models import DiscountPercentageConfig, DiscountRestrictionConfig class Disco...
raw_id_fields = ('course',) admin.site.register(DiscountRestrictionConfig, DiscountRestrictionConfigAdmin) class DiscountPercentageConfigAdmin(StackedConfigModelAdmin): """ Admin to configure discount percentage """ fieldsets = ( ('Context', { 'fields': DiscountRestrictionConf...
}) )
random_line_split
if_same_then_else.rs
#![warn(clippy::if_same_then_else)] #![allow( clippy::blacklisted_name, clippy::eq_op, clippy::never_loop, clippy::no_effect, clippy::unused_unit, clippy::zero_divided_by_zero, clippy::branches_sharing_code )] struct Foo { bar: u8, } fn foo() -> bool { unimplemented!() } fn if_sam...
() {}
main
identifier_name
if_same_then_else.rs
#![warn(clippy::if_same_then_else)] #![allow( clippy::blacklisted_name, clippy::eq_op, clippy::never_loop, clippy::no_effect, clippy::unused_unit, clippy::zero_divided_by_zero, clippy::branches_sharing_code )] struct Foo { bar: u8, } fn foo() -> bool { unimplemented!() } fn if_sam...
if true { Foo { bar: 42 }; } else { Foo { bar: 43 }; } if true { (); } else { () } if true { 0..10; } else { 0..=10; } if true { foo(); foo(); } else { foo(); } let _ = if true { 0.0 ...
{ if true { Foo { bar: 42 }; 0..10; ..; 0..; ..10; 0..=10; foo(); } else { //~ ERROR same body as `if` block Foo { bar: 42 }; 0..10; ..; 0..; ..10; 0..=10; foo(); }
identifier_body
if_same_then_else.rs
#![warn(clippy::if_same_then_else)] #![allow( clippy::blacklisted_name, clippy::eq_op, clippy::never_loop, clippy::no_effect, clippy::unused_unit, clippy::zero_divided_by_zero, clippy::branches_sharing_code )] struct Foo { bar: u8, } fn foo() -> bool { unimplemented!() } fn if_sam...
let _ = match 42 { 42 => 1, a if a > 0 => 2, 10..=15 => 3, _ => 4, }; } else if false { foo(); } else if foo() { let _ = match 42 { 42 => 1, a if a > 0 => 2, 10..=15 => 3, _ => 4, ...
} bar + 1; } if true {
random_line_split
if_same_then_else.rs
#![warn(clippy::if_same_then_else)] #![allow( clippy::blacklisted_name, clippy::eq_op, clippy::never_loop, clippy::no_effect, clippy::unused_unit, clippy::zero_divided_by_zero, clippy::branches_sharing_code )] struct Foo { bar: u8, } fn foo() -> bool { unimplemented!() } fn if_sam...
; if true { foo(); } let _ = if true { 42 } else { //~ ERROR same body as `if` block 42 }; if true { let bar = if true { 42 } else { 43 }; while foo() { break; } bar + 1; } else { //~ ERROR same body as `...
{ f32::NAN }
conditional_block
lib.rs
extern crate futures; extern crate rpassword; extern crate ethcore_util as util; extern crate bigint; extern crate parity_rpc as rpc; extern crate parity_rpc_client as client; use rpc::signer::{U256, ConfirmationRequest}; use client::signer_client::SignerRpc; use std::io::{Write, BufRead, BufReader, stdout, stdin}; ...
// cmds pub fn signer_list( signerport: u16, authfile: PathBuf ) -> Result<String, String> { let addr = &format!("ws://127.0.0.1:{}", signerport); let mut signer = SignerRpc::new(addr, &authfile).map_err(|err| { format!("{:?}", err) })?; list_transactions(&mut signer) } pub fn signer_reject( id: Option<usize>...
random_line_split
lib.rs
extern crate futures; extern crate rpassword; extern crate ethcore_util as util; extern crate bigint; extern crate parity_rpc as rpc; extern crate parity_rpc_client as client; use rpc::signer::{U256, ConfirmationRequest}; use client::signer_client::SignerRpc; use std::io::{Write, BufRead, BufReader, stdout, stdin}; ...
Ok(ref reqs) => { Ok(format!("Transaction queue:\n{}", reqs .iter() .map(|r| format!("{}", r)) .collect::<Vec<String>>() .join("\n"))) } Err(err) => { Err(format!("error: {:?}", err)) } } }).map_err(|err| { format!("{:?}", err) }).wait()? } fn sign_transac...
{ Ok("No transactions in signing queue".to_owned()) }
conditional_block
lib.rs
extern crate futures; extern crate rpassword; extern crate ethcore_util as util; extern crate bigint; extern crate parity_rpc as rpc; extern crate parity_rpc_client as client; use rpc::signer::{U256, ConfirmationRequest}; use client::signer_client::SignerRpc; use std::io::{Write, BufRead, BufReader, stdout, stdin}; ...
fn reject_transaction( signer: &mut SignerRpc, id: U256) -> Result<String, String> { signer.reject_request(id).map(|res| { match res { Ok(true) => Ok(format!("Rejected transaction id {:#x}", id)), Ok(false) => Err(format!("No such request")), Err(e) => Err(format!("{:?}", e)), } }).map_err(|err| { f...
{ signer.confirm_request(id, None, None, None, password).map(|res| { match res { Ok(u) => Ok(format!("Signed transaction id: {:#x}", u)), Err(e) => Err(format!("{:?}", e)), } }).map_err(|err| { format!("{:?}", err) }).wait()? }
identifier_body
lib.rs
extern crate futures; extern crate rpassword; extern crate ethcore_util as util; extern crate bigint; extern crate parity_rpc as rpc; extern crate parity_rpc_client as client; use rpc::signer::{U256, ConfirmationRequest}; use client::signer_client::SignerRpc; use std::io::{Write, BufRead, BufReader, stdout, stdin}; ...
( id: Option<usize>, signerport: u16, authfile: PathBuf ) -> Result<String, String> { let id = id.ok_or(format!("id required for signer reject"))?; let addr = &format!("ws://127.0.0.1:{}", signerport); let mut signer = SignerRpc::new(addr, &authfile).map_err(|err| { format!("{:?}", err) })?; reject_transaction(...
signer_reject
identifier_name
stemwords.py
import sys import re import codecs import snowballstemmer def usage(): print('''usage: %s [-l <language>] [-i <input file>] [-o <output file>] [-c <character encoding>] [-p[2]] [-h] The input file consists of a list of words to be stemmed, one per line. Words should be in lower case, but (for English) A-Z letters...
else: outfile.write("\n") outfile.write(" " * 30) outfile.write(stemmed) outfile.write('\n') outfile.close() main()
outfile.write(" " * (30 - len(original)))
conditional_block
stemwords.py
import sys import re import codecs import snowballstemmer def usage(): print('''usage: %s [-l <language>] [-i <input file>] [-o <output file>] [-c <character encoding>] [-p[2]] [-h] The input file consists of a list of words to be stemmed, one per line. Words should be in lower case, but (for English) A-Z letters...
outfile.write(original) if len(original) < 30: outfile.write(" " * (30 - len(original))) else: outfile.write("\n") outfile.write(" " * 30) outfile.write(stemmed) outfile.write('\n') outfile.close() main()
outfile.write(original, " -> ", stemmed) elif pretty == 2:
random_line_split
stemwords.py
import sys import re import codecs import snowballstemmer def usage():
def main(): argv = sys.argv[1:] if len(argv) < 5: usage() else: pretty = 0 input = '' output = '' encoding = 'utf_8' language = 'English' show_help = False while len(argv): arg = argv[0] argv = argv[1:] if ...
print('''usage: %s [-l <language>] [-i <input file>] [-o <output file>] [-c <character encoding>] [-p[2]] [-h] The input file consists of a list of words to be stemmed, one per line. Words should be in lower case, but (for English) A-Z letters are mapped to their a-z equivalents anyway. If omitted, stdin is used. If ...
identifier_body
stemwords.py
import sys import re import codecs import snowballstemmer def
(): print('''usage: %s [-l <language>] [-i <input file>] [-o <output file>] [-c <character encoding>] [-p[2]] [-h] The input file consists of a list of words to be stemmed, one per line. Words should be in lower case, but (for English) A-Z letters are mapped to their a-z equivalents anyway. If omitted, stdin is us...
usage
identifier_name
ident_md.py
# -*- coding: utf-8 -*- """
"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 Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright ...
Copyright (c) 2012 University of Oxford Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the
random_line_split
ident_md.py
# -*- coding: utf-8 -*- """ Copyright (c) 2012 University of Oxford 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, modif...
def add_metadata(self, environ, identity): userid = identity.get('repoze.who.userid') info = _DATA.get(userid) if info is not None: identity.update(info)
identifier_body
ident_md.py
# -*- coding: utf-8 -*- """ Copyright (c) 2012 University of Oxford 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, modif...
(object): def add_metadata(self, environ, identity): userid = identity.get('repoze.who.userid') info = _DATA.get(userid) if info is not None: identity.update(info)
IdentMDProvider
identifier_name
ident_md.py
# -*- coding: utf-8 -*- """ Copyright (c) 2012 University of Oxford 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, modif...
identity.update(info)
conditional_block
image.py
# -*- coding: utf-8 -*- # This file is part of CairoSVG # Copyright © 2010-2012 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option...
x, y = size(surface, node.get("x"), "x"), size(surface, node.get("y"), "y") width = size(surface, node.get("width"), "x") height = size(surface, node.get("height"), "y") surface.context.rectangle(x, y, width, height) surface.context.clip() if image_bytes[:4] == b"\x89PNG": png_file = B...
Draw an image ``node``.""" url = node.get("{http://www.w3.org/1999/xlink}href") if not url: return if url.startswith("data:"): image_bytes = open_data_url(url) else: base_url = node.get("{http://www.w3.org/XML/1998/namespace}base") if base_url: url = urlparse....
identifier_body
image.py
# -*- coding: utf-8 -*- # This file is part of CairoSVG # Copyright © 2010-2012 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option...
if url.startswith("data:"): image_bytes = open_data_url(url) else: base_url = node.get("{http://www.w3.org/XML/1998/namespace}base") if base_url: url = urlparse.urljoin(base_url, url) if node.url: url = urlparse.urljoin(node.url, url) if urlparse.url...
urn
conditional_block
image.py
# -*- coding: utf-8 -*- # This file is part of CairoSVG # Copyright © 2010-2012 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option...
url): """Decode URLs with the 'data' scheme. urllib can handle them in Python 2, but that is broken in Python 3. Inspired from Python 2.7.2’s urllib.py. """ # syntax of data URLs: # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data # mediatype := [ type "/" subtype ] *( ";" paramet...
pen_data_url(
identifier_name
image.py
# -*- coding: utf-8 -*- # This file is part of CairoSVG # Copyright © 2010-2012 Kozea # # This library is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option...
semi = header.rfind(";") if semi >= 0 and "=" not in header[semi:]: encoding = header[semi+1:] else: encoding = "" else: encoding = "" data = unquote_to_bytes(data) if encoding == "base64": missing_padding = 4 - len(data) % 4 if missin...
header = header[5:] # len("data:") == 5 if header:
random_line_split
view_wrapper.rs
use crate::direction::Direction; use crate::event::{AnyCb, Event, EventResult}; use crate::rect::Rect; use crate::view::{Selector, View}; use crate::Printer; use crate::Vec2; /// Generic wrapper around a view. /// /// This trait is a shortcut to implement `View` on a type by forwarding /// calls to a wrapped view. ///...
fn layout(&mut self, size: Vec2) { self.wrap_layout(size); } fn take_focus(&mut self, source: Direction) -> bool { self.wrap_take_focus(source) } fn call_on_any<'a>( &mut self, selector: &Selector<'_>, callback: AnyCb<'a>, ) { self.wrap_call_on...
{ self.wrap_on_event(ch) }
identifier_body
view_wrapper.rs
use crate::direction::Direction; use crate::event::{AnyCb, Event, EventResult}; use crate::rect::Rect; use crate::view::{Selector, View}; use crate::Printer; use crate::Vec2; /// Generic wrapper around a view. /// /// This trait is a shortcut to implement `View` on a type by forwarding /// calls to a wrapped view. ///...
/// Wraps the `on_event` method. fn wrap_on_event(&mut self, ch: Event) -> EventResult { self.with_view_mut(|v| v.on_event(ch)) .unwrap_or(EventResult::Ignored) } /// Wraps the `layout` method. fn wrap_layout(&mut self, size: Vec2) { self.with_view_mut(|v| v.layout(size...
random_line_split
view_wrapper.rs
use crate::direction::Direction; use crate::event::{AnyCb, Event, EventResult}; use crate::rect::Rect; use crate::view::{Selector, View}; use crate::Printer; use crate::Vec2; /// Generic wrapper around a view. /// /// This trait is a shortcut to implement `View` on a type by forwarding /// calls to a wrapped view. ///...
(&mut self, req: Vec2) -> Vec2 { self.wrap_required_size(req) } fn on_event(&mut self, ch: Event) -> EventResult { self.wrap_on_event(ch) } fn layout(&mut self, size: Vec2) { self.wrap_layout(size); } fn take_focus(&mut self, source: Direction) -> bool { self.w...
required_size
identifier_name
azure_rm_mariadbdatabase_info.py
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # Copyright (c) 2019 Matti Ranta, (@techknowlogick) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type AN...
(self): response = None results = [] try: response = self.mariadb_client.databases.list_by_server(resource_group_name=self.resource_group, server_name=self.server_name) self.log("Response : {0}".format(re...
list_by_server
identifier_name
azure_rm_mariadbdatabase_info.py
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # Copyright (c) 2019 Matti Ranta, (@techknowlogick) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type AN...
main()
conditional_block
azure_rm_mariadbdatabase_info.py
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # Copyright (c) 2019 Matti Ranta, (@techknowlogick) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type AN...
- name: List instances of MariaDB Database azure_rm_mariadbdatabase_info: resource_group: myResourceGroup server_name: server_name ''' RETURN = ''' databases: description: - A list of dictionaries containing facts for MariaDB Databases. returned: always type: complex contains:...
random_line_split
azure_rm_mariadbdatabase_info.py
#!/usr/bin/python # # Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.com> # Copyright (c) 2019 Matti Ranta, (@techknowlogick) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type AN...
def get(self): response = None results = [] try: response = self.mariadb_client.databases.get(resource_group_name=self.resource_group, server_name=self.server_name, ...
is_old_facts = self.module._name == 'azure_rm_mariadbdatabase_facts' if is_old_facts: self.module.deprecate("The 'azure_rm_mariadbdatabase_facts' module has been renamed to 'azure_rm_mariadbdatabase_info'", version='2.13') for key in self.module_arg_spec: setattr(self, key, kwar...
identifier_body
setup.py
#!/usr/bin/env python # flake8: noqa from setuptools import find_packages, setup setup( name = "acos-client", version = "1.4.6", packages = find_packages(), author = "A10 Networks", author_email = "mdurrant@a10networks.com", description = "A10 Networks ACOS API Client", license = "Apache"...
'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules' ], install_requires = ['requests>=2.3.0', 'six', 'uhashring'], test_suite="acos_client.tests.test_suite" )
'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy",
random_line_split
error.rs
OutOfMemory, "53300" => TooManyConnections, "53400" => ConfigurationLimitExceeded, // Class 54 — Program Limit Exceeded "54000" => ProgramLimitExceeded, "54001" => StatementTooComplex, "54011" => TooManyColumns, "54023" => TooManyArguments, // Class 55 — Object Not In Prerequisite Sta...
_>
identifier_name
error.rs
, "22002" => NullValueNoIndicatorParameter, "22003" => NumericValueOutOfRange, "22026" => StringDataLengthMismatch, "22001" => StringDataRightTruncationException, "22011" => SubstringError, "22027" => TrimError, "22024" => UnterminatedCString, "2200F" => ZeroLengthCharacterString, "2...
"57014" => QueryCanceled, "57P01" => AdminShutdown, "57P02" => CrashShutdown, "57P03" => CannotConnectNow,
random_line_split
internal.py
# -*- encoding: utf8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Marek Marczykowski-Górecki # <marmarek@invisiblethingslab.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
if processes: yield from asyncio.wait([p.wait() for p in processes]) coros = [] # then suspend/pause VMs for vm in self.app.domains: if isinstance(vm, qubes.vm.adminvm.AdminVM): continue if vm.is_running(): coros.append...
'' Method called before host system goes to sleep. :return: ''' # first notify all VMs processes = [] for vm in self.app.domains: if isinstance(vm, qubes.vm.adminvm.AdminVM): continue if vm.is_running(): proc = yie...
identifier_body
internal.py
# -*- encoding: utf8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Marek Marczykowski-Górecki # <marmarek@invisiblethingslab.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
self, untrusted_payload): ''' This is second half of admin.vm.volume.Import handling. It is called when actual import is finished. Response from this method is sent do the client (as a response for admin.vm.volume.Import call). ''' assert self.arg in self.dest.volumes.key...
m_volume_import_end(
identifier_name
internal.py
# -*- encoding: utf8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Marek Marczykowski-Górecki # <marmarek@invisiblethingslab.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
yield from asyncio.wait([p.wait() for p in processes])
random_line_split
internal.py
# -*- encoding: utf8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Marek Marczykowski-Górecki # <marmarek@invisiblethingslab.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
if coros: yield from asyncio.wait(coros) @qubes.api.method('internal.SuspendPost', no_payload=True) @asyncio.coroutine def suspend_post(self): ''' Method called after host system wake up from sleep. :return: ''' coros = [] # first resume...
oros.append(vm.suspend())
conditional_block
pydevd_xml.py
import pydev_log import traceback import pydevd_resolver from pydevd_constants import * #@UnusedWildImport from types import * #@UnusedWildImport try: from urllib import quote except: from urllib.parse import quote #@UnresolvedImport try: from xml.sax.saxutils import escape def makeValidXmlValue(s): ...
return type_object, type_name, pydevd_resolver.jyArrayResolver for t in typeMap: if isinstance(o, t[0]): return type_object, type_name, t[1] except: traceback.print_exc() #no match return default return type_object, type_name, pydevd_resolver.default...
""" returns a triple (typeObject, typeString, resolver resolver != None means that variable is a container, and should be displayed as a hierarchy. Use the resolver to get its attributes. All container objects should have a resolver. """ try: type_object = type(o) ...
identifier_body