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_nonlin.py
""" Unit tests for nonlinear solvers Author: Ondrej Certik May 2007 """ from numpy.testing import assert_, dec, TestCase, run_module_suite from scipy.optimize import nonlin from numpy import matrix, diag, dot from numpy.linalg import inv import numpy as np SOLVERS = [nonlin.anderson, nonlin.diagbroyden, nonlin.linea...
assert_(np.allclose(dx, jac.solve(df))) # Check that the `npoints` secant bound is strict if j >= npoints: dx = self.xs[j-npoints+1] - self.xs[j-npoints] df = self.fs[j-npoints+1] - self.fs[j-npoints] assert_(not np.allclose(dx, ja...
df = self.fs[j-k+1] - self.fs[j-k]
random_line_split
test_nonlin.py
""" Unit tests for nonlinear solvers Author: Ondrej Certik May 2007 """ from numpy.testing import assert_, dec, TestCase, run_module_suite from scipy.optimize import nonlin from numpy import matrix, diag, dot from numpy.linalg import inv import numpy as np SOLVERS = [nonlin.anderson, nonlin.diagbroyden, nonlin.linea...
if __name__ == "__main__": run_module_suite()
""" Test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) """ def test_broyden1(self): x= nonlin.broyden1(F,F.xin,iter=12,alpha=1) assert_(nonlin.norm(x) < 1e-9) ...
identifier_body
test_nonlin.py
""" Unit tests for nonlinear solvers Author: Ondrej Certik May 2007 """ from numpy.testing import assert_, dec, TestCase, run_module_suite from scipy.optimize import nonlin from numpy import matrix, diag, dot from numpy.linalg import inv import numpy as np SOLVERS = [nonlin.anderson, nonlin.diagbroyden, nonlin.linea...
if hasattr(jac, 'matvec') and hasattr(jac, 'solve'): Jv = jac.matvec(v) Jv2 = jac.solve(jac.matvec(Jv)) assert_close(Jv, Jv2, 'dot vs solve') if hasattr(jac, 'rmatvec') and hasattr(jac, 'rsolve'): Jv = jac.rmatvec(v) ...
Jv = jac.rmatvec(v) Jv2 = np.dot(Jd.T.conj(), v) assert_close(Jv, Jv2, 'rmatvec vs array')
conditional_block
test_poll.rs
use nix::{ Error, errno::Errno, poll::{PollFlags, poll, PollFd}, unistd::{write, pipe} }; macro_rules! loop_while_eintr { ($poll_expr: expr) => { loop { match $poll_expr { Ok(nfds) => break nfds, Err(Error::Sys(Errno::EINTR)) => (), ...
write(w, b".").unwrap(); // Poll a readable pipe. Should return an event. let nfds = poll(&mut fds, 100).unwrap(); assert_eq!(nfds, 1); assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN)); } // ppoll(2) is the same as poll except for how it handles timeouts and signals. // Repeating th...
random_line_split
test_poll.rs
use nix::{ Error, errno::Errno, poll::{PollFlags, poll, PollFd}, unistd::{write, pipe} }; macro_rules! loop_while_eintr { ($poll_expr: expr) => { loop { match $poll_expr { Ok(nfds) => break nfds, Err(Error::Sys(Errno::EINTR)) => (), ...
() { let (r, w) = pipe().unwrap(); let mut fds = [PollFd::new(r, PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout let nfds = loop_while_eintr!(poll(&mut fds, 100)); assert_eq!(nfds, 0); assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN)); write(w, b".").unwrap(); ...
test_poll
identifier_name
test_poll.rs
use nix::{ Error, errno::Errno, poll::{PollFlags, poll, PollFd}, unistd::{write, pipe} }; macro_rules! loop_while_eintr { ($poll_expr: expr) => { loop { match $poll_expr { Ok(nfds) => break nfds, Err(Error::Sys(Errno::EINTR)) => (), ...
// ppoll(2) is the same as poll except for how it handles timeouts and signals. // Repeating the test for poll(2) should be sufficient to check that our // bindings are correct. #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] #[test...
{ let (r, w) = pipe().unwrap(); let mut fds = [PollFd::new(r, PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout let nfds = loop_while_eintr!(poll(&mut fds, 100)); assert_eq!(nfds, 0); assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN)); write(w, b".").unwrap(); //...
identifier_body
conf.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
return d elif isinstance(value, dict): return value return None XMLSEC_BINARY = Config( key="xmlsec_binary", default="/usr/local/bin/xmlsec1", type=str, help=_t("Xmlsec1 binary path. This program should be executable by the user running Hue.")) ENTITY_ID = Config( key="entity_id", default="<...
d[k] = (v,)
conditional_block
conf.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
res.append(("libsaml.username_source", _("username_source not configured properly. SAML integration may not work."))) return res
def config_validator(user): res = [] if USERNAME_SOURCE.get() not in USERNAME_SOURCES:
random_line_split
conf.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
(user): res = [] if USERNAME_SOURCE.get() not in USERNAME_SOURCES: res.append(("libsaml.username_source", _("username_source not configured properly. SAML integration may not work."))) return res
config_validator
identifier_name
conf.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
XMLSEC_BINARY = Config( key="xmlsec_binary", default="/usr/local/bin/xmlsec1", type=str, help=_t("Xmlsec1 binary path. This program should be executable by the user running Hue.")) ENTITY_ID = Config( key="entity_id", default="<base_url>/saml2/metadata/", type=str, help=_t("Entity ID for Hue acting ...
if isinstance(value, str): d = {} for k, v in json.loads(value).iteritems(): d[k] = (v,) return d elif isinstance(value, dict): return value return None
identifier_body
tag-align-shape.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); debug!("y = %s", y); assert!(y == "(22, a_tag(44))"); }
main
identifier_name
tag-align-shape.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = {c8: 22u8, t: a_tag(44u64)}; let y = fmt!("%?", x); debug!("y = %s", y); assert!(y == "(22, a_tag(44))"); }
identifier_body
tag-align-shape.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
debug!("y = %s", y); assert!(y == "(22, a_tag(44))"); }
random_line_split
callbacks.rs
use std::panic; use std::ffi::CStr; use printf::printf; use alpm_sys::*; use libc::{c_int, c_char, c_void, off_t}; use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult}; use event::Event; /// Function with C calling convention and required type signature to wrap our callback pub unsafe extern "C"...
*/ pub unsafe extern "C" fn alpm_cb_totaldl(total: off_t) { let total = total as u64; panic::catch_unwind(|| { let mut cb = DLTOTAL_CB.lock().unwrap(); if let Some(ref mut cb) = *cb { cb(total); } }).unwrap_or(()) // ignore all errors since we are about to cross ffi boun...
random_line_split
callbacks.rs
use std::panic; use std::ffi::CStr; use printf::printf; use alpm_sys::*; use libc::{c_int, c_char, c_void, off_t}; use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult}; use event::Event; /// Function with C calling convention and required type signature to wrap our callback pub unsafe extern "C"...
(total: off_t) { let total = total as u64; panic::catch_unwind(|| { let mut cb = DLTOTAL_CB.lock().unwrap(); if let Some(ref mut cb) = *cb { cb(total); } }).unwrap_or(()) // ignore all errors since we are about to cross ffi boundary } /** A callback for downloading files...
alpm_cb_totaldl
identifier_name
callbacks.rs
use std::panic; use std::ffi::CStr; use printf::printf; use alpm_sys::*; use libc::{c_int, c_char, c_void, off_t}; use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult}; use event::Event; /// Function with C calling convention and required type signature to wrap our callback pub unsafe extern "C"...
{ let evt = Event::new(evt); panic::catch_unwind(|| { let mut cb = EVENT_CB.lock().unwrap(); if let Some(ref mut cb) = *cb { cb(evt); } }).unwrap_or(()) }
identifier_body
callbacks.rs
use std::panic; use std::ffi::CStr; use printf::printf; use alpm_sys::*; use libc::{c_int, c_char, c_void, off_t}; use {LOG_CB, DOWNLOAD_CB, DLTOTAL_CB, FETCH_CB, EVENT_CB, DownloadResult}; use event::Event; /// Function with C calling convention and required type signature to wrap our callback pub unsafe extern "C"...
}).unwrap_or(-1) // set error code if we have panicked } /** Event callback */ pub unsafe extern "C" fn alpm_cb_event(evt: *const alpm_event_t) { let evt = Event::new(evt); panic::catch_unwind(|| { let mut cb = EVENT_CB.lock().unwrap(); if let Some(ref mut cb) = *cb { cb(evt); ...
{ -1 }
conditional_block
generic_GetIPAddressV6.py
# -*- coding: utf-8 -*- """ ORCA Open Remote Control Application Copyright (C) 2013-2020 Carsten Thielepape Please contact me by : http://www.orca-remote.org/ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publi...
except Exception as e: Logger.error("Error on GetIPAddressV6:"+str(e)) if len(aFound)>0: uRet = aFound[-1] # remove stuff like %eth0 that gets thrown on end of some addrs uRet=uRet.split('%')[0] return uRet
aFound.append(uIP) if uNetiface == uPreferredAdapter: aFound = [uIP] break
conditional_block
generic_GetIPAddressV6.py
# -*- coding: utf-8 -*- """
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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will...
ORCA Open Remote Control Application Copyright (C) 2013-2020 Carsten Thielepape Please contact me by : http://www.orca-remote.org/
random_line_split
generic_GetIPAddressV6.py
# -*- coding: utf-8 -*- """ ORCA Open Remote Control Application Copyright (C) 2013-2020 Carsten Thielepape Please contact me by : http://www.orca-remote.org/ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publi...
uPreferredAdapter:str = u'eth0' uInet_Type:str = u'AF_INET6' uRet:str = u'127.0.0.0' aFound:List[str] = [] iInet_num:int try: iInet_num = getattr(netifaces, uInet_Type) aInterfaces:List = netifaces.interfaces() for uNetiface in aInterfaces...
identifier_body
generic_GetIPAddressV6.py
# -*- coding: utf-8 -*- """ ORCA Open Remote Control Application Copyright (C) 2013-2020 Carsten Thielepape Please contact me by : http://www.orca-remote.org/ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publi...
() -> str: uPreferredAdapter:str = u'eth0' uInet_Type:str = u'AF_INET6' uRet:str = u'127.0.0.0' aFound:List[str] = [] iInet_num:int try: iInet_num = getattr(netifaces, uInet_Type) aInterfaces:List = netifaces.interfaces() for uNetif...
GetIPAddressV6
identifier_name
views.py
import itertools as it from operator import attrgetter from flask import Markup, render_template, Blueprint, redirect, url_for, flash, abort, request from sqlalchemy import desc from .. import Execution, Stage, Task, TaskStatus from ..job.JobManager import JobManager from . import filters from ..graph.draw import dra...
@bprint.route('/execution/delete/<int:id>') def execution_delete(id): e = get_execution(id) e.delete(delete_files=True) flash('Deleted %s' % e) return redirect(url_for('cosmos.index')) @bprint.route('/') def index(): executions = session.query(Execution).order_b...
filters.add_filters(bprint)
random_line_split
views.py
import itertools as it from operator import attrgetter from flask import Markup, render_template, Blueprint, redirect, url_for, flash, abort, request from sqlalchemy import desc from .. import Execution, Stage, Task, TaskStatus from ..job.JobManager import JobManager from . import filters from ..graph.draw import dra...
profile_help = dict( # time system_time='Amount of time that this process has been scheduled in kernel mode', user_time='Amount of time that this process has been scheduled in user mode. This includes guest time, guest_time (time spent running a virtual CPU, see below), so that applications that ...
session = cosmos_app.session def get_execution(id): return session.query(Execution).filter_by(id=id).one() bprint = Blueprint('cosmos', __name__, template_folder='templates', static_folder='static', static_url_path='/cosmos/static') filters.add_filters(bprint) @bprint.r...
identifier_body
views.py
import itertools as it from operator import attrgetter from flask import Markup, render_template, Blueprint, redirect, url_for, flash, abort, request from sqlalchemy import desc from .. import Execution, Stage, Task, TaskStatus from ..job.JobManager import JobManager from . import filters from ..graph.draw import dra...
else: svg = 'Pygraphviz not installed, cannot visualize. (Usually: apt-get install graphviz && pip install pygraphviz)' return render_template('cosmos/taskgraph.html', execution=ex, type=type, svg=svg) # @bprint.route('/execution/<int:id>/taskgraph/svg/...
if type == 'task': svg = Markup(draw_task_graph(ex.task_graph(), url=True)) else: svg = Markup(draw_stage_graph(ex.stage_graph(), url=True))
conditional_block
views.py
import itertools as it from operator import attrgetter from flask import Markup, render_template, Blueprint, redirect, url_for, flash, abort, request from sqlalchemy import desc from .. import Execution, Stage, Task, TaskStatus from ..job.JobManager import JobManager from . import filters from ..graph.draw import dra...
(execution_name, stage_name): ex = session.query(Execution).filter_by(name=execution_name).one() stage = session.query(Stage).filter_by(execution_id=ex.id, name=stage_name).one() if stage is None: return abort(404) submitted = filter(lambda t: t.status == TaskStatus.submitted...
stage
identifier_name
main.py
# -*- coding: utf-8 -*- import datetime from kivy.app import App from kivy.uix.widget import Widget import random from kivy.clock import Clock from kivy.properties import StringProperty, NumericProperty from webScrape import webScraper class MirrorWindow(Widget): dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', ...
else: self.minute = 0.1 class MirrorApp(App): def build(self): mirrorWindow = MirrorWindow() Clock.schedule_interval(mirrorWindow.update, 0.01) return mirrorWindow if __name__ == '__main__': MirrorApp().run()
f.minute = self.minute + 0.1
conditional_block
main.py
# -*- coding: utf-8 -*- import datetime from kivy.app import App from kivy.uix.widget import Widget import random from kivy.clock import Clock from kivy.properties import StringProperty, NumericProperty from webScrape import webScraper class MirrorWindow(Widget): dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', ...
return mirrorWindow if __name__ == '__main__': MirrorApp().run()
random_line_split
main.py
# -*- coding: utf-8 -*- import datetime from kivy.app import App from kivy.uix.widget import Widget import random from kivy.clock import Clock from kivy.properties import StringProperty, NumericProperty from webScrape import webScraper class MirrorWindow(Widget): dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', ...
if __name__ == '__main__': MirrorApp().run()
rorWindow = MirrorWindow() Clock.schedule_interval(mirrorWindow.update, 0.01) return mirrorWindow
identifier_body
main.py
# -*- coding: utf-8 -*- import datetime from kivy.app import App from kivy.uix.widget import Widget import random from kivy.clock import Clock from kivy.properties import StringProperty, NumericProperty from webScrape import webScraper class MirrorWindow(Widget): dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', ...
lf, dt): self.time = datetime.datetime.today().strftime("%H:%M") self.day = self.dayPrint[int(datetime.date.today().strftime('%w'))] self.date = datetime.date.today().strftime('%y%m%d') #self.seconds = str (( int (datetime.datetime.today().strftime('%f')) / 1000 ) ) #self.seconds...
ate(se
identifier_name
TileImage.ts
module Terrain.Tiles { export class TileImage { private static instance: TileImage; private north: number; private west: number; private tileSize: number; private gridSize: number; private miniMap: HTMLElement; constructor(tileSize: number, gridSiz...
} private OnImageLoaded(data: any): void { if (data) { TileImage.GetExistingInstance().miniMap.setAttribute("src", "data:image/bmp;base64," + data); } } } }
tilesHttpClient.GetTileImage({ NorthLalitude: this.north, WestLongitude: this.west }, this.OnImageLoaded); }
random_line_split
TileImage.ts
module Terrain.Tiles { export class TileImage { private static instance: TileImage; private north: number; private west: number; private tileSize: number; private gridSize: number; private miniMap: HTMLElement; constructor(tileSize: number, gridSiz...
} } }
TileImage.GetExistingInstance().miniMap.setAttribute("src", "data:image/bmp;base64," + data); }
conditional_block
TileImage.ts
module Terrain.Tiles { export class Ti
private static instance: TileImage; private north: number; private west: number; private tileSize: number; private gridSize: number; private miniMap: HTMLElement; constructor(tileSize: number, gridSize: number, miniMap: HTMLElement) { this.t...
leImage {
identifier_name
scopeTests.ts
///<reference path='..\..\..\..\src\compiler\typescript.ts' /> ///<reference path='..\..\..\..\src\harness\harness.ts' /> describe('Compiling tests\\compiler\\scopeTests.ts', function() { it("Scope check extended class with errors", function () { var code = 'class C { private v; public p; static s; }...
assert.arrayLengthIs(result.errors, 1); assert.compilerWarning(result, 1, 49, "error TS2141: Class 'D' cannot extend class 'C':\r\n\tProperty 'v' defined as public in type 'D' is defined as private in type 'C'."); } ); } ); });
code += ' C.s = 1;'; code += ' }'; code += '}'; Harness.Compiler.compileString(code, 'declarations', function (result) {
random_line_split
NavCogLogFunction.js
var _logFunction = new $NavCogLogFunction(); $(document).ready(function() { document.getElementById("log-data-chooser").addEventListener("change", _logFunction.loadFile); }); function $NavCogLogFunction() { var logLocations = []; function loadFile(e) { logLocations = []; var file = this.files[0]; if (file) ...
(edge) { for (var i = 0; i < logLocations.length; i++) { var log = logLocations[i]; if (log.edge == edge.id) { var marker = logLocations[i].marker; if (!marker) { var node1 = _currentLayer.nodes[edge.node1], node2 = _currentLayer.nodes[edge.node2]; var info1 = node1.infoFromEdges[edge.id], inf...
drawMarkers
identifier_name
NavCogLogFunction.js
var _logFunction = new $NavCogLogFunction(); $(document).ready(function() { document.getElementById("log-data-chooser").addEventListener("change", _logFunction.loadFile); }); function $NavCogLogFunction() { var logLocations = []; function loadFile(e)
function parseLogData(text) { text.split("\n").forEach(function(line, i) { if (line) { var params = line.match(/(.*?) (.*?) (.*?) (.*)/); if (params && params.length == 5) { var msgs = params[4].split(","); var obj; switch (msgs[0]) { case "FoundCurrentLocation": obj = { ...
{ logLocations = []; var file = this.files[0]; if (file) { var fr = new FileReader(); fr.addEventListener("load", function(e) { parseLogData(fr.result); }); fr.readAsText(file); } }
identifier_body
NavCogLogFunction.js
var _logFunction = new $NavCogLogFunction(); $(document).ready(function() { document.getElementById("log-data-chooser").addEventListener("change", _logFunction.loadFile); }); function $NavCogLogFunction() { var logLocations = []; function loadFile(e) { logLocations = []; var file = this.files[0]; if (file) ...
coords : [ 12.5, 12.5, 25 ], type : "circle", }; options.labelAnchor = new google.maps.Point(10.5, 6.25); } logLocations[i].marker = marker = new MarkerWithLabel(options); } marker.setMap(_map); } } } $editor.on("derender", function(e, layer) { for (var i = 0; i < l...
random_line_split
NavCogLogFunction.js
var _logFunction = new $NavCogLogFunction(); $(document).ready(function() { document.getElementById("log-data-chooser").addEventListener("change", _logFunction.loadFile); }); function $NavCogLogFunction() { var logLocations = []; function loadFile(e) { logLocations = []; var file = this.files[0]; if (file) ...
} } $editor.on("derender", function(e, layer) { for (var i = 0; i < logLocations.length; i++) { var marker = logLocations[i].marker; if (marker) { marker.setMap(null); } } }); return { "loadFile" : loadFile, "renderLayer" : renderLayer }; }
{ var marker = logLocations[i].marker; if (!marker) { var node1 = _currentLayer.nodes[edge.node1], node2 = _currentLayer.nodes[edge.node2]; var info1 = node1.infoFromEdges[edge.id], info2 = node2.infoFromEdges[edge.id] // console.log(log); // console.log(edge); // console.log(node1); ...
conditional_block
entries.rs
use std::env; use std::error::Error; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use controllers::prelude::*; use models::{queries, Tag}; use views; use util; use aqua_web::plug; use aqua_web::mw::forms::{MultipartForm, SavedFile}; use aqua_web::mw::router::Router; use...
pub fn show_thumb(conn: &mut plug::Conn) { let file_id = Router::param::<i64>(conn, "id") .expect("missing route param: id"); match queries::find_entry(conn, file_id) { Ok(entry) => { let glob_pattern = glob_for_category("t", &entry.hash); info!("glob pattern: {}", glo...
{ let file_id = Router::param::<i64>(conn, "id") .expect("missing route param: id"); match queries::find_entry(conn, file_id) { Ok(entry) => { let glob_pattern = glob_for_category("f", &entry.hash); info!("glob pattern: {}", glob_pattern); let paths = glob(&...
identifier_body
entries.rs
use std::env; use std::error::Error; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf};
use views; use util; use aqua_web::plug; use aqua_web::mw::forms::{MultipartForm, SavedFile}; use aqua_web::mw::router::Router; use glob::glob; use image::{self, FilterType, ImageFormat, ImageResult}; use serde_json; #[derive(Serialize)] struct TagView { tags: Vec<Tag>, } fn glob_for_category(category: &str, dig...
use controllers::prelude::*; use models::{queries, Tag};
random_line_split
entries.rs
use std::env; use std::error::Error; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use controllers::prelude::*; use models::{queries, Tag}; use views; use util; use aqua_web::plug; use aqua_web::mw::forms::{MultipartForm, SavedFile}; use aqua_web::mw::router::Router; use...
(conn: &mut plug::Conn) { // TODO: handle webm, etc. use models::queries; // TODO: simpler way to get extensions let mut form_fields = { conn.req_mut().mut_extensions().pop::<MultipartForm>() }; // NOTE: these are separate b/c we need to hang on to the file ref ... let file_upload = form_fi...
submit
identifier_name
DiscreteCNACache.ts
import _ from 'lodash'; import { AugmentedData, CacheData, default as LazyMobXCache, } from 'shared/lib/LazyMobXCache'; import client from 'shared/api/cbioportalClientInstance'; import { DiscreteCopyNumberData, DiscreteCopyNumberFilter, MolecularProfile, } from 'cbioportal-ts-api-client'; expor...
}) ); return { data: _.flatten(allData), meta: studyId }; } catch (err) { throw err; } } export function fetch( queries: Query[], studyToMolecularProfileDiscrete: { [studyId: string]: MolecularProfile } ): Promise<AugmentedData<DiscreteCopyNumberData, string>[]> { ...
{ return client.fetchDiscreteCopyNumbersInMolecularProfileUsingPOST( { projection: 'DETAILED', molecularProfileId: molecularProfileIdDiscrete, discreteCopyNumberFilter: filter, ...
conditional_block
DiscreteCNACache.ts
import _ from 'lodash'; import { AugmentedData, CacheData, default as LazyMobXCache, } from 'shared/lib/LazyMobXCache'; import client from 'shared/api/cbioportalClientInstance'; import { DiscreteCopyNumberData, DiscreteCopyNumberFilter, MolecularProfile, } from 'cbioportal-ts-api-client'; expor...
( queries: Query[], studyId: string, molecularProfileIdDiscrete: string | undefined ): Promise<AugmentedData<DiscreteCopyNumberData, string>> { try { const uniqueSamples = _.uniq(queries.map(q => q.sampleId)); const uniqueGenes = _.uniq(queries.map(q => q.entrezGeneId)); let filt...
fetchForStudy
identifier_name
DiscreteCNACache.ts
import _ from 'lodash'; import { AugmentedData, CacheData, default as LazyMobXCache, } from 'shared/lib/LazyMobXCache'; import client from 'shared/api/cbioportalClientInstance'; import { DiscreteCopyNumberData, DiscreteCopyNumberFilter, MolecularProfile, } from 'cbioportal-ts-api-client'; expor...
export function fetch( queries: Query[], studyToMolecularProfileDiscrete: { [studyId: string]: MolecularProfile } ): Promise<AugmentedData<DiscreteCopyNumberData, string>[]> { if (!studyToMolecularProfileDiscrete) { throw 'No study to molecular profile id map given'; } else { const stud...
{ try { const uniqueSamples = _.uniq(queries.map(q => q.sampleId)); const uniqueGenes = _.uniq(queries.map(q => q.entrezGeneId)); let filters: DiscreteCopyNumberFilter[]; if (uniqueSamples.length < uniqueGenes.length) { // Make one query per sample, since there are fewer ...
identifier_body
DiscreteCNACache.ts
import _ from 'lodash'; import { AugmentedData, CacheData, default as LazyMobXCache, } from 'shared/lib/LazyMobXCache'; import client from 'shared/api/cbioportalClientInstance'; import { DiscreteCopyNumberData, DiscreteCopyNumberFilter, MolecularProfile, } from 'cbioportal-ts-api-client'; expor...
} ); } }) ); return { data: _.flatten(allData), meta: studyId }; } catch (err) { throw err; } } export function fetch( queries: Query[], studyToMolecularProfileDiscrete: { [studyId: string]: MolecularProfile ...
{ projection: 'DETAILED', molecularProfileId: molecularProfileIdDiscrete, discreteCopyNumberFilter: filter, discreteCopyNumberEventType: 'ALL',
random_line_split
delete-dialog.buildconfig.component.ts
import { Component } from '@angular/core'; import { BuildConfig } from '../../../model/buildconfig.model'; import { BuildConfigService } from '../../../service/buildconfig.service'; import { BuildConfigStore } from '../../../store/buildconfig.store'; @Component({ selector: 'delete-buildconfig-dialog', templateUrl:...
close() { this.modal.close(); } }
{ this.modal.close(); const stream = this.buildconfigService.delete(this.buildconfig); if (stream) { stream.subscribe( () => { // }, (err) => { console.log('delete failed: ', err); this.buildconfigStore.loadAll(); }, () => { ...
identifier_body
delete-dialog.buildconfig.component.ts
import { Component } from '@angular/core'; import { BuildConfig } from '../../../model/buildconfig.model'; import { BuildConfigService } from '../../../service/buildconfig.service';
styleUrls: ['./delete-dialog.buildconfig.component.less'], }) export class BuildConfigDeleteDialog { buildconfig: BuildConfig = new BuildConfig(); modal: any; constructor( private buildconfigService: BuildConfigService, private buildconfigStore: BuildConfigStore, ) {} ok() { this.modal.close(...
import { BuildConfigStore } from '../../../store/buildconfig.store'; @Component({ selector: 'delete-buildconfig-dialog', templateUrl: './delete-dialog.buildconfig.component.html',
random_line_split
delete-dialog.buildconfig.component.ts
import { Component } from '@angular/core'; import { BuildConfig } from '../../../model/buildconfig.model'; import { BuildConfigService } from '../../../service/buildconfig.service'; import { BuildConfigStore } from '../../../store/buildconfig.store'; @Component({ selector: 'delete-buildconfig-dialog', templateUrl:...
else { this.buildconfigStore.loadAll(); } } close() { this.modal.close(); } }
{ stream.subscribe( () => { // }, (err) => { console.log('delete failed: ', err); this.buildconfigStore.loadAll(); }, () => { this.buildconfigStore.loadAll(); }, ); }
conditional_block
delete-dialog.buildconfig.component.ts
import { Component } from '@angular/core'; import { BuildConfig } from '../../../model/buildconfig.model'; import { BuildConfigService } from '../../../service/buildconfig.service'; import { BuildConfigStore } from '../../../store/buildconfig.store'; @Component({ selector: 'delete-buildconfig-dialog', templateUrl:...
() { this.modal.close(); const stream = this.buildconfigService.delete(this.buildconfig); if (stream) { stream.subscribe( () => { // }, (err) => { console.log('delete failed: ', err); this.buildconfigStore.loadAll(); }, () => { ...
ok
identifier_name
zattooDB.py
# coding=utf-8 # # copyright (C) 2017 Steffen Rolapp (github@rolapp.de) # # based on ZattooBoxExtended by Daniel Griner (griner.ch@gmail.com) license under GPL # # This file is part of ZattooHiQ # # zattooHiQ is free software: you can redistribute it and/or modify # it under the terms of the GNU...
def connectSQL(self): import sqlite3 sqlite3.register_adapter(datetime.datetime, self.adapt_datetime) sqlite3.register_converter('timestamp', self.convert_datetime) self.conn = sqlite3.connect(self.databasePath, detect_types=sqlite3.PARSE_DECLTYPES) self.conn.execute('PRAGMA foreign_keys ...
return datetime.datetime.fromtimestamp(float(ts)) except ValueError: return None
identifier_body
zattooDB.py
# coding=utf-8 # # copyright (C) 2017 Steffen Rolapp (github@rolapp.de) # # based on ZattooBoxExtended by Daniel Griner (griner.ch@gmail.com) license under GPL # # This file is part of ZattooHiQ # # zattooHiQ is free software: you can redistribute it and/or modify # it under the terms of the GNU...
PopUp.create('zattooHiQ lade Programm Informationen ...', '') PopUp.update(bar) for chan in channels['index']: print str(chan) + ' - ' + str(startTime) c.execute('SELECT * FROM programs WHERE channel = ? AND start_date < ? AND end_date > ?', [chan, endTime...
c.execute('SELECT * FROM programs WHERE channel = ? AND start_date < ? AND end_date > ?', [chan, endTime, startTime]) r=c.fetchall() for row in r: counter += 1 bar = 0 # Progressbar (Null Prozent)
random_line_split
zattooDB.py
# coding=utf-8 # # copyright (C) 2017 Steffen Rolapp (github@rolapp.de) # # based on ZattooBoxExtended by Daniel Griner (griner.ch@gmail.com) license under GPL # # This file is part of ZattooHiQ # # zattooHiQ is free software: you can redistribute it and/or modify # it under the terms of the GNU...
for chan in channels['index']: print str(chan) + ' - ' + str(startTime) c.execute('SELECT * FROM programs WHERE channel = ? AND start_date < ? AND end_date > ?', [chan, endTime, startTime]) r=c.fetchall() for row in r: print str(row['chann...
p = xbmcgui.DialogProgressBG() #counter = len(channels) counter = 0 for chan in channels['index']: c.execute('SELECT * FROM programs WHERE channel = ? AND start_date < ? AND end_date > ?', [chan, endTime, startTime]) r=c.fetchall() ...
conditional_block
zattooDB.py
# coding=utf-8 # # copyright (C) 2017 Steffen Rolapp (github@rolapp.de) # # based on ZattooBoxExtended by Daniel Griner (griner.ch@gmail.com) license under GPL # # This file is part of ZattooHiQ # # zattooHiQ is free software: you can redistribute it and/or modify # it under the terms of the GNU...
f, showID): info = self.conn.cursor() try: info.execute('SELECT * FROM programs WHERE showID= ? ', [showID]) except: info.close() return None show = info.fetchone() longDesc = show['description_long'] year = show['year'] ...
howLongDescription(sel
identifier_name
internal.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { experimental, json } from '@angular-devkit/core'; import { BuilderInfo, BuilderInput, BuilderOutput, Target ...
/** * BuilderVersionSymbol used for knowing which version of the library createBuilder() came from. * This is to make sure we don't try to use an incompatible builder. * Using Symbol.for() as it's a global registry that's the same for all installations of * Architect (if some libraries depends directly on architec...
* property set on the function that should be `true`. * Using Symbol.for() as it's a global registry that's the same for all installations of * Architect (if some libraries depends directly on architect instead of sharing the files). */ export const BuilderSymbol = Symbol.for('@angular-devkit/architect:builder');
random_line_split
variable.rs
use std::fmt; use path::Path; pub struct
{ name: String, is_new_declaration: bool, is_global: bool } impl VariableAssignment { pub fn new(name: String, is_new_declaration: bool, is_global: bool) -> VariableAssignment { VariableAssignment { name: name, is_new_declaration: is_new_declaration, is_glob...
VariableAssignment
identifier_name
variable.rs
use std::fmt; use path::Path; pub struct VariableAssignment { name: String, is_new_declaration: bool, is_global: bool } impl VariableAssignment { pub fn new(name: String, is_new_declaration: bool, is_global: bool) -> VariableAssignment { VariableAssignment { name: name, ...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "var({})", self.name) } } pub struct ReadCount { target: Path } impl ReadCount { pub fn new(target: Path) -> ReadCount { ReadCount { target: target } } pub fn target(&self) -> &Path { ...
random_line_split
variable.rs
use std::fmt; use path::Path; pub struct VariableAssignment { name: String, is_new_declaration: bool, is_global: bool } impl VariableAssignment { pub fn new(name: String, is_new_declaration: bool, is_global: bool) -> VariableAssignment { VariableAssignment { name: name, ...
pub fn is_new_declaration(&self) -> bool { self.is_new_declaration } pub fn is_global(&self) -> bool { self.is_global } pub fn set_is_global(&mut self, is_global: bool) { self.is_global = is_global } } impl fmt::Display for VariableAssignment { fn fmt(&self, f: &...
{ &self.name }
identifier_body
testsws.js
/* Copyright (C) 2017 Innotrade GmbH <https://innotrade.com> 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 ...
}); });
});
random_line_split
es.js
{ "ALLOWED_FILE_TYPE": "Only following files are allowed : ", "AUTHORIZATION_REQUIRED": "No estás autorizado para usar el administrador de archivos.", "DIRECTORY_ALREADY_EXISTS": "La carpeta '%s' ya existe.", "DIRECTORY_NOT_EXIST": "La carpeta %s no existe.", "DISALLOWED_FILE_TYPE": "Following f...
"mb": "mb", "modified": "Modificado", "move": "Move to ...", "name": "Nombre", "new_filename": "Introduce un nuevo nombre para el archivo", "new_folder": "Nueva carpeta", "no": "No", "no_foldername": "No se ha indicado un nombre para la carpeta.", "parentfolder": "Directorio ...
"gb": "gb", "grid_view": "Cambiar a vista de cuadrícula.", "kb": "kb", "list_view": "Cambiar a vista de lista.", "loading_data": "Transferring data ...",
random_line_split
winevt.py
# -*- coding: utf-8 -*- """Parser for Windows EventLog (EVT) files.""" import pyevt from plaso import dependencies from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.lib import specification from plaso.parsers import interface from plaso.parsers import manager...
def _ParseRecord( self, parser_mediator, record_index, evt_record, recovered=False): """Extract data from a Windows EventLog (EVT) record. Args: parser_mediator: a parser mediator object (instance of ParserMediator). record_index: the event record index. evt_record: an event record (...
""" format_specification = specification.FormatSpecification(cls.NAME) format_specification.AddNewSignature(b'LfLe', offset=4) return format_specification
random_line_split
winevt.py
# -*- coding: utf-8 -*- """Parser for Windows EventLog (EVT) files.""" import pyevt from plaso import dependencies from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.lib import specification from plaso.parsers import interface from plaso.parsers import manager...
manager.ParsersManager.RegisterParser(WinEvtParser)
"""Parses a Windows EventLog (EVT) file-like object. Args: parser_mediator: a parser mediator object (instance of ParserMediator). file_object: a file-like object. Raises: UnableToParseFile: when the file cannot be parsed. """ evt_file = pyevt.file() evt_file.set_ascii_codepage(p...
identifier_body
winevt.py
# -*- coding: utf-8 -*- """Parser for Windows EventLog (EVT) files.""" import pyevt from plaso import dependencies from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.lib import specification from plaso.parsers import interface from plaso.parsers import manager...
try: written_time = evt_record.get_written_time_as_integer() except OverflowError as exception: parser_mediator.ProduceParseError(( u'unable to read written time from event record: {0:d} ' u'with error: {1:s}').format(record_index, exception)) written_time = None if...
event_object = WinEvtRecordEvent( creation_time, eventdata.EventTimestamp.CREATION_TIME, evt_record, record_number, event_identifier, recovered=recovered) parser_mediator.ProduceEvent(event_object)
conditional_block
winevt.py
# -*- coding: utf-8 -*- """Parser for Windows EventLog (EVT) files.""" import pyevt from plaso import dependencies from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.lib import specification from plaso.parsers import interface from plaso.parsers import manager...
(time_events.PosixTimeEvent): """Convenience class for a Windows EventLog (EVT) record event. Attributes: computer_name: the computer name stored in the event record. event_category: the event category. event_identifier: the event identifier. event_type: the event type. facility: the event faci...
WinEvtRecordEvent
identifier_name
baseplugin.py
""" BasePlugin definitions. """ import logging import threading import traceback import os import queue from sjutils import threadpool class BasePluginError(Exception): """Raised by BasePlugin.""" def __init__(self, error): """Init method.""" Exception.__init__(self, error) class BasePlugi...
"status": status, } ], None, request_id=status["status_id"], callback=self.job_stop, exc_callback=self.handle_ex...
"group": checks["groups"][status["grp_id"]], "object": checks["objects"][str(status["obj_id"])],
random_line_split
baseplugin.py
""" BasePlugin definitions. """ import logging import threading import traceback import os import queue from sjutils import threadpool class BasePluginError(Exception): """Raised by BasePlugin.""" def __init__(self, error): """Init method.""" Exception.__init__(self, error) class BasePlugi...
if checks.get("status", None) is None: self.log.error("remote module did not return any work") continue if len(checks["status"]) > 0: self.log.debug("got %s checks" % len(checks["status"])) # Queue checks ...
continue
conditional_block
baseplugin.py
""" BasePlugin definitions. """ import logging import threading import traceback import os import queue from sjutils import threadpool class BasePluginError(Exception): """Raised by BasePlugin.""" def __init__(self, error): """Init method.""" Exception.__init__(self, error) class BasePlugi...
@staticmethod def __prepare_status_update(check): """Prepare a structure for status update.""" status = { "status_id": check["status"]["status_id"], "sequence_id": check["status"]["seq_id"], "status": check["status"]["check_status"], "message": c...
return "<BasePlugin>"
identifier_body
baseplugin.py
""" BasePlugin definitions. """ import logging import threading import traceback import os import queue from sjutils import threadpool class BasePluginError(Exception): """Raised by BasePlugin.""" def
(self, error): """Init method.""" Exception.__init__(self, error) class BasePlugin(threading.Thread): """Base class for job implementation in spvd.""" name = "" require = {} optional = { "debug": bool, "max_parallel_checks": int, "max_checks_queue": int, ...
__init__
identifier_name
karma.conf.js
// Karma configuration // Generated on Sat Jul 04 2015 21:07:22 GMT-0300 (BRT) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/k...
// start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }) }
random_line_split
main.py
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.models.website import unslug from openerp.tools import DEFAULT_SERVER_DATE_FORMAT from openerp.tools.translate import _ import time import werkzeug.urls ...
else: membership_line_ids = [] country_domain = [('membership_state', '=', 'free')] if post_name: country_domain += ['|', ('name', 'ilike', post_name), ('website_description', 'ilike', post_name)] countries = partner_obj.read_...
country_domain = ['|', country_domain[0], ('membership_state', '=', 'free')]
random_line_split
main.py
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.models.website import unslug from openerp.tools import DEFAULT_SERVER_DATE_FORMAT from openerp.tools.translate import _ import time import werkzeug.urls ...
_, partner_id = unslug(partner_id) if partner_id: partner = request.registry['res.partner'].browse(request.cr, SUPERUSER_ID, partner_id, context=request.context) if partner.exists() and partner.website_published: values = {} values['main_object'] = values[...
identifier_body
main.py
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.models.website import unslug from openerp.tools import DEFAULT_SERVER_DATE_FORMAT from openerp.tools.translate import _ import time import werkzeug.urls ...
(self, membership_id=None, country_name=None, country_id=0, page=1, **post): cr, uid, context = request.cr, request.uid, request.context product_obj = request.registry['product.product'] country_obj = request.registry['res.country'] membership_line_obj = request.registry['membership.memb...
members
identifier_name
main.py
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.addons.web import http from openerp.addons.web.http import request from openerp.addons.website.models.website import unslug from openerp.tools import DEFAULT_SERVER_DATE_FORMAT from openerp.tools.translate import _ import time import werkzeug.urls ...
else: membership_line_ids = [] country_domain = [('membership_state', '=', 'free')] if post_name: country_domain += ['|', ('name', 'ilike', post_name), ('website_description', 'ilike', post_name)] countries = partner_obj.read...
country_domain = ['|', country_domain[0], ('membership_state', '=', 'free')]
conditional_block
ALPHA3.py
# Copyright (c) 2003-2010, Berend-Jan "SkyLined" Wever <berendjanwever@gmail.com> # Project homepage: http://code.google.com/p/alpha3/ # All rights reserved. See COPYRIGHT.txt for details. import charsets, encode, io import x86, x64, test import os, re, sys #_____________________________________________________...
def PrintHelp(): PrintInfo([ (None, "[Usage]"), (" ", "ALPHA3.py [ encoder settings | I/O settings | flags ]"), (None, ""), (None, "[Encoder setting]"), (" architecture ", "Which processor architecture to target (x86, x64)."), (" character encoding ", "Which character encodi...
PrintInfo([ (None, "____________________________________________________________________________"), (None, """ ,sSSs,,s, ,sSSSs, ALPHA3 - Alphanumeric shellcode encoder."""), (None, """ dS" Y$P" YS" ,SY Version 1.0 alpha"""), (None, """ iS' dY ssS" Copyright (C) 200...
identifier_body
ALPHA3.py
# Copyright (c) 2003-2010, Berend-Jan "SkyLined" Wever <berendjanwever@gmail.com> # Project homepage: http://code.google.com/p/alpha3/ # All rights reserved. See COPYRIGHT.txt for details. import charsets, encode, io import x86, x64, test import os, re, sys #_____________________________________________________...
elif _flags["help"]: encoder_settings_string = "%s %s %s" % (encoder_settings["architecture"], encoder_settings["character encoding"], encoder_settings["case"]); if encoder_settings_string not in help_results: help_results[encoder_settings_string] = []; ...
at_least_one_encoder_found = True; results.extend(problems); errors = True;
conditional_block
ALPHA3.py
# Copyright (c) 2003-2010, Berend-Jan "SkyLined" Wever <berendjanwever@gmail.com> # Project homepage: http://code.google.com/p/alpha3/ # All rights reserved. See COPYRIGHT.txt for details. import charsets, encode, io import x86, x64, test import os, re, sys #_____________________________________________________...
(): PrintInfo([ (None, "____________________________________________________________________________"), (None, """ ,sSSs,,s, ,sSSSs, ALPHA3 - Alphanumeric shellcode encoder."""), (None, """ dS" Y$P" YS" ,SY Version 1.0 alpha"""), (None, """ iS' dY ssS" Copyright ...
PrintLogo
identifier_name
ALPHA3.py
# Copyright (c) 2003-2010, Berend-Jan "SkyLined" Wever <berendjanwever@gmail.com> # Project homepage: http://code.google.com/p/alpha3/ # All rights reserved. See COPYRIGHT.txt for details. import charsets, encode, io import x86, x64, test import os, re, sys #_____________________________________________________...
(" --help", "Display this message and quit."), (" --test", "Run all available tests for all encoders. (Useful while developing/testing new " "encoders)."), (" --int3", "Trigger a breakpoint before executing the result of a test. (Use in comb...
random_line_split
docker_autostop_test.py
try: from unittest import mock except ImportError: import mock from docker_custodian.docker_autostop import ( build_container_matcher, get_opts, has_been_running_since, main, stop_container, stop_containers, ) def test_stop_containers(mock_client, container, now): matcher = mock.M...
stop_container(mock_client, id) mock_client.stop.assert_called_once_with(id) def test_build_container_matcher(): prefixes = ['one_', 'two_'] matcher = build_container_matcher(prefixes) assert matcher('one_container') assert matcher('two_container') assert not matcher('three_container') ...
mock_client.stop.assert_called_once_with(container['Id']) def test_stop_container(mock_client): id = 'asdb'
random_line_split
docker_autostop_test.py
try: from unittest import mock except ImportError: import mock from docker_custodian.docker_autostop import ( build_container_matcher, get_opts, has_been_running_since, main, stop_container, stop_containers, ) def test_stop_containers(mock_client, container, now):
def test_stop_container(mock_client): id = 'asdb' stop_container(mock_client, id) mock_client.stop.assert_called_once_with(id) def test_build_container_matcher(): prefixes = ['one_', 'two_'] matcher = build_container_matcher(prefixes) assert matcher('one_container') assert matcher('two...
matcher = mock.Mock() mock_client.containers.return_value = [container] mock_client.inspect_container.return_value = container stop_containers(mock_client, now, matcher, False) matcher.assert_called_once_with('container_name') mock_client.stop.assert_called_once_with(container['Id'])
identifier_body
docker_autostop_test.py
try: from unittest import mock except ImportError: import mock from docker_custodian.docker_autostop import ( build_container_matcher, get_opts, has_been_running_since, main, stop_container, stop_containers, ) def test_stop_containers(mock_client, container, now): matcher = mock.M...
(now): with mock.patch( 'docker_custodian.docker_autostop.timedelta_type', autospec=True ) as mock_timedelta_type: opts = get_opts(args=['--prefix', 'one', '--max-run-time', '24h']) assert opts.max_run_time == mock_timedelta_type.return_value mock_timedelta_type.assert_called_onc...
test_get_opts_with_args
identifier_name
UiPasswordPlugin.py
import string import random import time import json import re from Config import config from Plugin import PluginManager if "sessions" not in locals().keys(): # To keep sessions between module reloads sessions = {} def showPasswordAdvice(password): error_msgs = [] if not password or not isinstance(pass...
# Valid password, create session session_id = self.randomString(26) self.sessions[session_id] = { "added": time.time(), "keep": posted.get("keep") } # Redirect to homepage or referer ...
posted = self.getPosted() if posted: # Validate http posted data if self.checkPassword(posted.get("password")):
random_line_split
UiPasswordPlugin.py
import string import random import time import json import re from Config import config from Plugin import PluginManager if "sessions" not in locals().keys(): # To keep sessions between module reloads sessions = {} def showPasswordAdvice(password): error_msgs = [] if not password or not isinstance(pass...
elif len(password) < 8: error_msgs.append("You are using a very short UI password!") return error_msgs @PluginManager.registerTo("UiRequest") class UiRequestPlugin(object): sessions = sessions last_cleanup = time.time() def route(self, path): if path.endswith("favicon.ico"): ...
error_msgs.append("You have enabled <b>UiPassword</b> plugin, but you forgot to set a password!")
conditional_block
UiPasswordPlugin.py
import string import random import time import json import re from Config import config from Plugin import PluginManager if "sessions" not in locals().keys(): # To keep sessions between module reloads sessions = {} def showPasswordAdvice(password): error_msgs = [] if not password or not isinstance(pass...
# Action: Logout def actionLogout(self): # Session id has to passed as get parameter or called without referer to avoid remote logout session_id = self.getCookies().get("session_id") if not self.env.get("HTTP_REFERER") or session_id == self.get.get("session_id"): if session...
self.sendHeader() yield "<pre>" yield json.dumps(self.sessions, indent=4)
identifier_body
UiPasswordPlugin.py
import string import random import time import json import re from Config import config from Plugin import PluginManager if "sessions" not in locals().keys(): # To keep sessions between module reloads sessions = {} def showPasswordAdvice(password): error_msgs = [] if not password or not isinstance(pass...
(self): template = open("plugins/UiPassword/login.html").read() self.sendHeader() posted = self.getPosted() if posted: # Validate http posted data if self.checkPassword(posted.get("password")): # Valid password, create session session_id = sel...
actionLogin
identifier_name
optimize.py
import sys import typing import click import glotaran as gta from . import util @click.option('--dataformat', '-dfmt', default=None, type=click.Choice(gta.io.reader.known_reading_formats.keys()), help='The input format of the data. Will be infered from extension if not set.') @click.opti...
"""Optimizes a model. e.g.: glotaran optimize -- """ if scheme is not None: scheme = util.load_scheme_file(scheme, verbose=True) if nfev is not None: scheme.nfev = nfev else: if model is None: click.echo('Error: Neither scheme nor model specified', er...
identifier_body
optimize.py
import sys import typing import click import glotaran as gta from . import util @click.option('--dataformat', '-dfmt', default=None, type=click.Choice(gta.io.reader.known_reading_formats.keys()), help='The input format of the data. Will be infered from extension if not set.') @click.opti...
click.echo('All done, have a nice day!')
try: click.echo(f"Saving directory is '{out}'") if yes or click.confirm('Do you want to save the data?', default=True): paths = result.save(out) click.echo(f"File saving successfull, the follwing files have been written:\n") for...
conditional_block
optimize.py
import sys import typing import click import glotaran as gta from . import util @click.option('--dataformat', '-dfmt', default=None, type=click.Choice(gta.io.reader.known_reading_formats.keys()), help='The input format of the data. Will be infered from extension if not set.') @click.opti...
(dataformat: str, data: typing.List[str], out: str, nfev: int, nnls: bool, yes: bool, parameter: str, model: str, scheme: str): """Optimizes a model. e.g.: glotaran optimize -- """ if scheme is not None: scheme = util.load_scheme_file(scheme, verbose=True) if nfev i...
optimize_cmd
identifier_name
optimize.py
import glotaran as gta from . import util @click.option('--dataformat', '-dfmt', default=None, type=click.Choice(gta.io.reader.known_reading_formats.keys()), help='The input format of the data. Will be infered from extension if not set.') @click.option('--data', '-d', multiple=True, ...
import sys import typing import click
random_line_split
fakekms_test.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
assert!(client.supported(key_uri)); let primitive = client.get_aead(key_uri).unwrap(); let plaintext = b"some data to encrypt"; let aad = b"extra data to authenticate"; let ciphertext = primitive.encrypt(&plaintext[..], &aad[..]).unwrap(); let decrypted = primitive.decry...
random_line_split
fakekms_test.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
#[test] fn test_invalid_prefix() { tink_aead::init(); let uri_prefix = "fake-kms://CM2x"; // is not a prefix of KEY_URI let client = FakeClient::new(uri_prefix).unwrap(); assert!(!client.supported(KEY_URI)); assert!(client.get_aead(KEY_URI).is_err()); } #[test] fn test_get_aead_fails_with_bad_key...
{ tink_aead::init(); let uri_prefix = "fake-kms://CM2b"; // is a prefix of KEY_URI let client = FakeClient::new(uri_prefix).unwrap(); assert!(client.supported(KEY_URI)); let result = client.get_aead(KEY_URI); assert!(result.is_ok(), "{:?}", result.err()); }
identifier_body
fakekms_test.rs
// Copyright 2020 The Tink-Rust Authors // // 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 ag...
() { tink_aead::init(); let uri_prefix = "fake-kms://CM2b"; // is a prefix of KEY_URI let client = FakeClient::new(uri_prefix).unwrap(); assert!(client.supported(KEY_URI)); let result = client.get_aead(KEY_URI); assert!(result.is_ok(), "{:?}", result.err()); } #[test] fn test_invalid_prefix() {...
test_valid_prefix
identifier_name
ebill_payment_contract.py
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class EbillPaymentContract(models.Model):
paynet_account_number = fields.Char(string="Paynet ID", size=20) is_paynet_contract = fields.Boolean( compute="_compute_is_paynet_contract", store=False ) paynet_service_id = fields.Many2one( comodel_name="paynet.service", string="Paynet Service", ondelete="restrict" ) payment_ty...
_inherit = "ebill.payment.contract"
random_line_split
ebill_payment_contract.py
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class EbillPaymentContract(models.Model): _inherit = "ebill.payment.contract" paynet_account_number = fields.Char(string="Paynet ...
(self): for contract in self: if contract.is_paynet_contract and not contract.paynet_service_id: raise ValidationError( _("A Paynet service is required for a Paynet contract.") )
_check_paynet_service_id
identifier_name
ebill_payment_contract.py
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class EbillPaymentContract(models.Model):
_inherit = "ebill.payment.contract" paynet_account_number = fields.Char(string="Paynet ID", size=20) is_paynet_contract = fields.Boolean( compute="_compute_is_paynet_contract", store=False ) paynet_service_id = fields.Many2one( comodel_name="paynet.service", string="Paynet Service", ond...
identifier_body
ebill_payment_contract.py
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class EbillPaymentContract(models.Model): _inherit = "ebill.payment.contract" paynet_account_number = fields.Char(string="Paynet ...
@api.constrains("transmit_method_id", "paynet_account_number") def _check_paynet_account_number(self): for contract in self: if not contract.is_paynet_contract: continue if not contract.paynet_account_number: raise ValidationError( ...
record.is_paynet_contract = record.transmit_method_id == transmit_method
conditional_block
viewer-impl.js
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
/** * Returns the promise that will yield the confirmed "referrer" URL. This * URL can be optionally customized by the viewer, but viewer is required * to be a trusted viewer. * @return {!Promise<string>} */ getReferrerUrl() { return this.referrerUrl_; } /** * Whether the viewer has bee...
{ return this.unconfirmedReferrerUrl_; }
identifier_body
viewer-impl.js
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
this.messagingMaybePromise_ = this.isEmbedded_ ? this.messagingReadyPromise_ .catch(reason => { // Don't fail promise, but still report. reportError(getChannelError( /** @type {!Error|string|undefined} */ (reason))); }) : null; // Tr...
* deliver if at all possible. This promise is only available when the * document is embedded. * @private @const {?Promise} */
random_line_split
viewer-impl.js
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
() { return this.referrerUrl_; } /** * Whether the viewer has been whitelisted for more sensitive operations * such as customizing referrer. * @return {!Promise<boolean>} */ isTrustedViewer() { return this.isTrustedViewer_; } /** * Returns the promise that resolves to URL representing...
getReferrerUrl
identifier_name
project.ts
import { Organization } from './organization'; import { Company } from './company'; import { Team } from './team'; import { Status } from './status'; export class Project extends Organization { public description: string; public survey_key: string; public survey_mode: number; public company_id: number; publi...
(): boolean { return true; } }
isProject
identifier_name
project.ts
import { Organization } from './organization'; import { Company } from './company'; import { Team } from './team'; import { Status } from './status'; export class Project extends Organization { public description: string; public survey_key: string; public survey_mode: number; public company_id: number; publi...
isProject(): boolean { return true; } }
{ return 'P' + this.id; }
identifier_body
project.ts
import { Organization } from './organization'; import { Company } from './company'; import { Team } from './team'; import { Status } from './status'; export class Project extends Organization { public description: string; public survey_key: string; public survey_mode: number; public company_id: number; publi...
} get uniqueId(): string { return 'P' + this.id; } isProject(): boolean { return true; } }
{ values.statuses.forEach((status) => { this.statuses.push(new Status(status)); }); }
conditional_block
project.ts
import { Organization } from './organization'; import { Company } from './company'; import { Team } from './team'; import { Status } from './status'; export class Project extends Organization { public description: string; public survey_key: string; public survey_mode: number; public company_id: number; publi...
this.teams.push(newTeam); }); } if (values.statuses) { values.statuses.forEach((status) => { this.statuses.push(new Status(status)); }); } } get uniqueId(): string { return 'P' + this.id; } isProject(): boolean { return true; } }
if (values.teams) { values.teams.forEach((team) => { let newTeam: Team = new Team(team); newTeam.project = this;
random_line_split