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
createuser.py
# 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/. """ Create a user. """ from django.contrib.auth.models import User from django.core.management.base import BaseCommand ...
(self, **options): username = options["username"] password = options["password"] email = options["email"] if User.objects.filter(username=username).exists(): self.stdout.write("User {} already exists.".format(username)) return user = User.objects.create(...
handle
identifier_name
createuser.py
# 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/.
Create a user. """ from django.contrib.auth.models import User from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Create a user." def add_arguments(self, parser): parser.add_argument("username", help="account username") parser.add_argument("password", hel...
"""
random_line_split
event_box.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! GtkEventBox — A widget used to catch events for widgets which do not have their own windo...
self) -> bool { unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) } } } impl_drop!(EventBox); impl_TraitWidget!(EventBox); impl ::ContainerTrait for EventBox {} impl ::BinTrait for EventBox {}
t_visible_window(&
identifier_name
event_box.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! GtkEventBox — A widget used to catch events for widgets which do not have their own windo...
} impl_drop!(EventBox); impl_TraitWidget!(EventBox); impl ::ContainerTrait for EventBox {} impl ::BinTrait for EventBox {}
pub fn get_visible_window(&self) -> bool { unsafe { to_bool(ffi::gtk_event_box_get_visible_window(GTK_EVENT_BOX(self.pointer))) } }
random_line_split
event_box.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! GtkEventBox — A widget used to catch events for widgets which do not have their own windo...
pub fn get_above_child(&self) -> bool { unsafe { to_bool(ffi::gtk_event_box_get_above_child(GTK_EVENT_BOX(self.pointer))) } } pub fn set_visible_window(&self, visible_window: bool) { unsafe { ffi::gtk_event_box_set_visible_window(GTK_EVENT_BOX(self.pointer), to_gboolean(visible_...
unsafe { ffi::gtk_event_box_set_above_child(GTK_EVENT_BOX(self.pointer), to_gboolean(above_child)) } }
identifier_body
medlemsinput.py
# Graphical paste and save GUI for adding members from Tkinter import * import os import pdb import datetime lday = 04 lmonth = 10 class myDate: def __init__(self, year, month, day): self.date = datetime.datetime(year, month, day) self.updateString() def getMonthDay(self): lday = for...
return fstr root = Tk() text = Text(root) text.insert(INSERT, "") text.bind("<Control-Key-a>", select_all) text.grid() bsave = Button(root, text="Save", command=lambda: save(date)) bsave.grid(columnspan=2, column=1, row=0) dplus = Button(root, text="d+", command=lambda: add_day(date)) dplus.grid(column=1, row=...
first = first + 1 fstr = format(first, '02')
conditional_block
medlemsinput.py
# Graphical paste and save GUI for adding members from Tkinter import * import os import pdb import datetime lday = 04 lmonth = 10 class myDate: def __init__(self, year, month, day): self.date = datetime.datetime(year, month, day) self.updateString() def getMonthDay(self): lday = for...
first = first + 1 fstr = format(first, '02') return fstr root = Tk() text = Text(root) text.insert(INSERT, "") text.bind("<Control-Key-a>", select_all) text.grid() bsave = Button(root, text="Save", command=lambda: save(date)) bsave.grid(columnspan=2, column=1, row=0) dplus = Button(root, text="d...
random_line_split
medlemsinput.py
# Graphical paste and save GUI for adding members from Tkinter import * import os import pdb import datetime lday = 04 lmonth = 10 class myDate: def __init__(self, year, month, day): self.date = datetime.datetime(year, month, day) self.updateString() def getMonthDay(self): lday = for...
def select_all(event): text.tag_add(SEL, "1.0", END) text.mark_set(INSERT, "1.0") text.see(INSERT) return 'break' def nextfname(prefix): first = 1 fstr = format(first, '02') while os.path.exists(prefix + "-" + fstr + ".txt"): first = first + 1 fstr = format...
dt = datetime.datetime(2015, date.date.month, date.date.day) dt = dt - datetime.timedelta(days=1) date.updateDate(dt) date.updateString() lfname = date.getfilename() llabel.configure(text = lfname)
identifier_body
medlemsinput.py
# Graphical paste and save GUI for adding members from Tkinter import * import os import pdb import datetime lday = 04 lmonth = 10 class myDate: def __init__(self, year, month, day): self.date = datetime.datetime(year, month, day) self.updateString() def getMonthDay(self): lday = for...
(date): f = open(date.getfilename(), "w") t = text.get("1.0", END) f.write(t.encode('utf8')) f.close() lfname = date.getfilename() llabel.configure(text = lfname) def add_day(date): dt = datetime.datetime(2015, date.date.month, date.date.day) dt = dt + datetime.timedelta(days=1) dat...
save
identifier_name
test_gfxBlacklist_OK.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ // This should eventually be moved to head_addons.js var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; // Test whether a machine which exactly matches the blacklist entry is // successf...
// Performs the initial setup function run_test() { var gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo); // We can't do anything if we can't spoof the stuff we need. if (!(gfxInfo instanceof Ci.nsIGfxInfoDebug)) { do_test_finished(); return; } gfxInfo.QueryInterface(Ci.nsIGfxInfo...
{ Services.prefs.setCharPref("extensions.blocklist.url", "http://localhost:" + gPort + "/data/" + file); var blocklist = Cc["@mozilla.org/extensions/blocklist;1"]. getService(Ci.nsITimerCallback); blocklist.notify(null); }
identifier_body
test_gfxBlacklist_OK.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ // This should eventually be moved to head_addons.js var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; // Test whether a machine which exactly matches the blacklist entry is // successf...
gfxInfo.QueryInterface(Ci.nsIGfxInfoDebug); // Set the vendor/device ID, etc, to match the test file. switch (get_platform()) { case "WINNT": gfxInfo.spoofVendorID("0xabcd"); gfxInfo.spoofDeviceID("0x1234"); gfxInfo.spoofDriverVersion("8.52.322.2201"); // Windows 7 gfxInfo.spo...
{ do_test_finished(); return; }
conditional_block
test_gfxBlacklist_OK.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ // This should eventually be moved to head_addons.js var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; // Test whether a machine which exactly matches the blacklist entry is // successf...
() { var xulRuntime = Cc["@mozilla.org/xre/app-info;1"] .getService(Ci.nsIXULRuntime); return xulRuntime.OS; } function load_blocklist(file) { Services.prefs.setCharPref("extensions.blocklist.url", "http://localhost:" + gPort + "/data/" + file); var blo...
get_platform
identifier_name
test_gfxBlacklist_OK.js
/* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ // This should eventually be moved to head_addons.js var { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; // Test whether a machine which exactly matches the blacklist entry is // successf...
function load_blocklist(file) { Services.prefs.setCharPref("extensions.blocklist.url", "http://localhost:" + gPort + "/data/" + file); var blocklist = Cc["@mozilla.org/extensions/blocklist;1"]. getService(Ci.nsITimerCallback); blocklist.notify(null); } // Performs t...
.getService(Ci.nsIXULRuntime); return xulRuntime.OS; }
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
# This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the G...
# # This program 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) version 2.1, February 1999. #
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""FontAwesome icons in PyQt and PySide applications""" homepage = "https://github.com/spyder-ide/qtawesome" url = "https://pypi.io/packages/source/Q/QtAwesome/QtAwesome-0.4.1.tar.gz" version('0.4.1', 'bf93df612a31f3b501d751fc994c1b05') version('0.3.3', '830677aa6ca4e7014e228147475183d3') depends...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(PythonPackage): """FontAwesome icons in PyQt and PySide applications""" homepage = "https://github.com/spyder-ide/qtawesome" url = "https://pypi.io/packages/source/Q/QtAwesome/QtAwesome-0.4.1.tar.gz" version('0.4.1', 'bf93df612a31f3b501d751fc994c1b05') version('0.3.3', '830677aa6ca4e7014e22814747...
PyQtawesome
identifier_name
tables.py
from horizon import tables from django.utils.translation import ugettext_lazy as _ import utils import whisper import time def get_vcpu_load_avgs(instance): cpu_files = utils.get_whisper_files_by_metric( "cpu", utils.get_whisper_files_by_instance_id(instance.id)) if not cpu_fi...
class MonitorTable(tables.DataTable): name = tables.Column("name", #link=("horizon:project:instances:detail"), link=("horizon:nova:instances_and_volumes:instances:detail"), verbose_name=_("Instance Name")) host = tables.Column("OS-EXT...
mem_files = utils.get_whisper_files_by_metric( "mem", utils.get_whisper_files_by_instance_id(instance.id)) if not mem_files: return "N/A" fetched = whisper.fetch(mem_files[0], time.time() - back) times, data = fetched for val in reversed(data): if val i...
identifier_body
tables.py
from horizon import tables from django.utils.translation import ugettext_lazy as _ import utils import whisper import time def get_vcpu_load_avgs(instance): cpu_files = utils.get_whisper_files_by_metric( "cpu", utils.get_whisper_files_by_instance_id(instance.id)) if not cpu_fi...
: name = 'instances' verbose_name = _("Instances")
Meta
identifier_name
tables.py
from horizon import tables from django.utils.translation import ugettext_lazy as _ import utils import whisper import time def get_vcpu_load_avgs(instance): cpu_files = utils.get_whisper_files_by_metric( "cpu", utils.get_whisper_files_by_instance_id(instance.id)) if not cpu_fi...
# TODO: what if we have more than one CPU database?? fetched = whisper.fetch(cpu_files[0], time.time() - back) times, data = fetched # return the most recent data point that's not None for val in reversed(data): if val is not None: return val * 100 return "N/A" def get_...
return "N/A"
conditional_block
tables.py
from horizon import tables from django.utils.translation import ugettext_lazy as _ import utils import whisper import time def get_vcpu_load_avgs(instance): cpu_files = utils.get_whisper_files_by_metric( "cpu", utils.get_whisper_files_by_instance_id(instance.id)) if not cpu_fi...
if not mem_files: return "N/A" fetched = whisper.fetch(mem_files[0], time.time() - back) times, data = fetched for val in reversed(data): if val is not None: return val * 100 return "N/A" class MonitorTable(tables.DataTable): name = tables.Column("name", ...
"mem", utils.get_whisper_files_by_instance_id(instance.id))
random_line_split
dpapi.rs
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
pOptionalEntropy: *mut DATA_BLOB, pvReserved: PVOID, pPromptStruct: *mut CRYPTPROTECT_PROMPTSTRUCT, dwFlags: DWORD, pDataOut: *mut DATA_BLOB, ) -> BOOL; pub fn CryptProtectDataNoUI( pDataIn: *mut DATA_BLOB, szDataDescr: LPCWSTR, pOptionalEntropy: *...
pDataIn: *mut DATA_BLOB, ppszDataDescr: *mut LPWSTR,
random_line_split
page-position.service.ts
import { Injectable } from '@angular/core'; import { get, floor, isEqual } from 'lodash'; import { MATRIX_GRID_CONTAINER_CLASS } from '../../defaultState'; import { UrlParametersService } from '../../url-parameters/url-parameters.service'; @Injectable() export class PagePositionService { gridContainer: HTMLElement;...
else { document.documentElement.scrollTop = 0; } } }
{ document.body.scrollTop = 0; }
conditional_block
page-position.service.ts
import { Injectable } from '@angular/core'; import { get, floor, isEqual } from 'lodash'; import { MATRIX_GRID_CONTAINER_CLASS } from '../../defaultState'; import { UrlParametersService } from '../../url-parameters/url-parameters.service'; @Injectable() export class PagePositionService { gridContainer: HTMLElement;...
constructor(private urlParametersService: UrlParametersService) { } findGridContainer(): HTMLElement { const matrixContainer = document.querySelector(`.${MATRIX_GRID_CONTAINER_CLASS}`) as HTMLElement; if (!isEqual(this.gridContainer, matrixContainer)) { this.gridContainer = matrixContainer; }...
{ return this.row; }
identifier_body
page-position.service.ts
import { Injectable } from '@angular/core'; import { get, floor, isEqual } from 'lodash'; import { MATRIX_GRID_CONTAINER_CLASS } from '../../defaultState'; import { UrlParametersService } from '../../url-parameters/url-parameters.service'; @Injectable() export class PagePositionService { gridContainer: HTMLElement;...
(size) { this._itemSize = size; } get currentRow(): number { return this.row; } constructor(private urlParametersService: UrlParametersService) { } findGridContainer(): HTMLElement { const matrixContainer = document.querySelector(`.${MATRIX_GRID_CONTAINER_CLASS}`) as HTMLElement; if (!isE...
itemSize
identifier_name
page-position.service.ts
import { Injectable } from '@angular/core'; import { get, floor, isEqual } from 'lodash'; import { MATRIX_GRID_CONTAINER_CLASS } from '../../defaultState'; import { UrlParametersService } from '../../url-parameters/url-parameters.service'; @Injectable() export class PagePositionService { gridContainer: HTMLElement;...
document.documentElement.scrollTop = 0; } } }
if (document.body.scrollTop) { document.body.scrollTop = 0; } else {
random_line_split
min-max-resolution.js
goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.control'); goog.require('ol.layer.Tile'); goog.require('ol.source.OSM'); goog.require('ol.source.TileJSON'); /** * Create the map. */
source: new ol.source.OSM(), minResolution: 200, maxResolution: 2000 }), new ol.layer.Tile({ source: new ol.source.TileJSON({ url: 'https://api.tiles.mapbox.com/v3/mapbox.natural-earth-hypso-bathy.json?secure', crossOrigin: 'anonymous' }), minResolution: 2000,...
var map = new ol.Map({ layers: [ new ol.layer.Tile({
random_line_split
htmltableelement.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::attr::{Attr, AttrHelpers, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTML...
} fn before_remove_attr(&self, attr: JSRef<Attr>) { if let Some(ref s) = self.super_type() { s.before_remove_attr(attr); } match attr.local_name() { &atom!("bgcolor") => self.background_color.set(None), &atom!("border") => self.border.set(None), ...
{ if let Some(ref s) = self.super_type() { s.after_set_attr(attr); } match attr.local_name() { &atom!("bgcolor") => { self.background_color.set(str::parse_legacy_color(&attr.value()).ok()) } &atom!("border") => { //...
identifier_body
htmltableelement.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::attr::{Attr, AttrHelpers, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTML...
(&self) -> Option<u32> { self.border.get() } fn get_cellspacing(&self) -> Option<u32> { self.cellspacing.get() } fn get_width(&self) -> LengthOrPercentageOrAuto { self.width.get() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> { fn super_type<'b>(&'b self)...
get_border
identifier_name
htmltableelement.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::attr::{Attr, AttrHelpers, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding::HTML...
fn get_width(&self) -> LengthOrPercentageOrAuto { self.width.get() } } impl<'a> VirtualMethods for JSRef<'a, HTMLTableElement> { fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self); Some(htmlele...
} fn get_cellspacing(&self) -> Option<u32> { self.cellspacing.get() }
random_line_split
object-lifetime-default-from-rptr-mut.rs
// run-pass // Test that the lifetime of the enclosing `&` is used for the object // lifetime bound. // pretty-expanded FIXME #23616 #![allow(dead_code)] trait Test { fn foo(&self) { } } struct SomeStruct<'a> { t: &'a mut dyn Test, u: &'a mut (dyn Test+'a), } fn a<'a>(t: &'a mut dyn Test, mut ss: SomeS...
<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) { ss.u = t; } fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) { ss.t = t; } fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) { ss.u = t; } fn main() { }
b
identifier_name
object-lifetime-default-from-rptr-mut.rs
// run-pass // Test that the lifetime of the enclosing `&` is used for the object // lifetime bound. // pretty-expanded FIXME #23616 #![allow(dead_code)]
trait Test { fn foo(&self) { } } struct SomeStruct<'a> { t: &'a mut dyn Test, u: &'a mut (dyn Test+'a), } fn a<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) { ss.t = t; } fn b<'a>(t: &'a mut dyn Test, mut ss: SomeStruct<'a>) { ss.u = t; } fn c<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<...
random_line_split
object-lifetime-default-from-rptr-mut.rs
// run-pass // Test that the lifetime of the enclosing `&` is used for the object // lifetime bound. // pretty-expanded FIXME #23616 #![allow(dead_code)] trait Test { fn foo(&self) { } } struct SomeStruct<'a> { t: &'a mut dyn Test, u: &'a mut (dyn Test+'a), } fn a<'a>(t: &'a mut dyn Test, mut ss: SomeS...
fn d<'a>(t: &'a mut (dyn Test+'a), mut ss: SomeStruct<'a>) { ss.u = t; } fn main() { }
{ ss.t = t; }
identifier_body
fileBlockService.js
const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); function FileBlock()
FileBlock.prototype = { appDir: null, profileDir: null, tempDir: null, // List of domains for the whitelist whitelist: [], // Chrome pages that should not be shown chromeBlacklist: ["browser", "mozapps", "marionette", "specialpowers", "branding", "alerts"], initialize: function() {...
{}
identifier_body
fileBlockService.js
const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); function
() {} FileBlock.prototype = { appDir: null, profileDir: null, tempDir: null, // List of domains for the whitelist whitelist: [], // Chrome pages that should not be shown chromeBlacklist: ["browser", "mozapps", "marionette", "specialpowers", "branding", "alerts"], initialize: functio...
FileBlock
identifier_name
fileBlockService.js
const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); function FileBlock() {} FileBlock.prototype = { appDir: null, profileDir: null, tempDir: null, // List of domains for the whitelist whitelist: [...
// Deny all files if (aContentLocation.scheme == "file") { return Ci.nsIContentPolicy.REJECT_REQUEST; } // Allow view source // if (aContentLocation.scheme == "view-source") { // return Ci.nsIContentPolicy.ACCEPT; // } // If we had a whitelist, reject everything else if (this.w...
{ return Ci.nsIContentPolicy.ACCEPT; }
conditional_block
fileBlockService.js
const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); function FileBlock() {} FileBlock.prototype = { appDir: null, profileDir: null, tempDir: null, // List of domains for the whitelist whitelist: [...
for (var i=0; i < this.whitelist.length; i++) { this.whitelist[i] = this.whitelist[i].trim(); } } catch(e) {} var whitelistFile = profileDir.clone(); whitelistFile.append("webconverger.whitelist"); if (!whitelistFile.exists()) { return; } var stream = Cc["@mozilla.org/...
this.whitelist = whitelist.split(",");
random_line_split
engine.io-tests.ts
import engine = require('engine.io'); import http = require('http'); let serverOptions: engine.ServerOptions; let server: engine.Server; let httpServer: http.Server; let attachOptions: engine.AttachOptions; let serverAttachOptions: engine.ServerAttachOptions; serverOptions = {}; serverOptions = { pingTimeout: 60000,...
attachOptions.handlePreflightRequest = (server, req, res) => { console.log(server.clientsCount); console.log(req.httpVersion); console.log(res.finished); }; serverAttachOptions = { ...serverOptions, ...attachOptions }; console.log(engine.protocol); httpServer = http.createServer(); httpServer.listen(8000); server...
destroyUpgradeTimeout: 1000, }; attachOptions.handlePreflightRequest = true; attachOptions.handlePreflightRequest = false;
random_line_split
common.py
import codecs import itertools import re import textwrap import tokenize from abc import abstractmethod from collections import Sequence from twitter.common.lang import Compatibility, Interface __all__ = ( 'CheckstylePlugin', 'PythonFile', ) class OffByOneList(Sequence): def __init__(self, iterator): # ...
(object): """Checkstyle wrapper for Python source files.""" SKIP_TOKENS = frozenset((tokenize.COMMENT, tokenize.NL, tokenize.DEDENT)) def _remove_coding_header(self, blob): """ There is a bug in ast.parse that cause it to throw a syntax error if you have a header similar to... # coding=utf-8, ...
PythonFile
identifier_name
common.py
import codecs import itertools import re import textwrap import tokenize from abc import abstractmethod from collections import Sequence from twitter.common.lang import Compatibility, Interface __all__ = ( 'CheckstylePlugin', 'PythonFile', ) class OffByOneList(Sequence): def __init__(self, iterator): # ...
def enumerate(self): """Return an enumeration of line_number, line pairs.""" return enumerate(self, 1) class Nit(object): """Encapsulate a Style faux pas. The general taxonomy of nits: Prefix F => Flake8 errors E => PEP8 error W => PEP8 warning T => Twitter error Prefix: 0 N...
start, stop, _ = self.logical_lines[line_number] return slice(start, stop)
conditional_block
common.py
): return len(self._list) def __getitem__(self, element_id): if isinstance(element_id, Compatibility.integer): return self.__get_list_item(element_id) elif isinstance(element_id, slice): return self.__getslice(element_id) raise TypeError('__getitem__ only supports integers and slices') ...
return self.nit(code, Nit.WARNING, message, line_number_or_ast)
identifier_body
common.py
import codecs import itertools import re import textwrap import tokenize from abc import abstractmethod from collections import Sequence from twitter.common.lang import Compatibility, Interface __all__ = ( 'CheckstylePlugin', 'PythonFile', ) class OffByOneList(Sequence): def __init__(self, iterator): # ...
def enumerate(self): """Return an enumeration of line_number, line pairs.""" return enumerate(self, 1) class Nit(object): """Encapsulate a Style faux pas. The general taxonomy of nits: Prefix F => Flake8 errors E => PEP8 error W => PEP8 warning T => Twitter error Prefix: 0 Nam...
return slice(start, stop)
random_line_split
turing.py
required_states = ['accept', 'reject', 'init'] class TuringMachine(object): def __init__(self, sigma, gamma, delta): self.sigma = sigma self.gamma = gamma self.delta = delta self.state = None self.tape = None self.head_position = None return ...
return str(self.tape)
def run(self, input_string, verbose=False): self.initialize(input_string) while self.state not in ['reject', 'accept']: self.simulate_one_step(verbose)
random_line_split
turing.py
required_states = ['accept', 'reject', 'init'] class TuringMachine(object):
def simulate_one_step(self, verbose=False): if self.state in ['accept', 'reject']: print "# %s " % self.state cur_symbol = self.tape[self.head_position] transition = self.delta[(self.state, cur_symbol)] if verbose: ...
def __init__(self, sigma, gamma, delta): self.sigma = sigma self.gamma = gamma self.delta = delta self.state = None self.tape = None self.head_position = None return def initialize(self, input_string): for char in input_string: ...
identifier_body
turing.py
required_states = ['accept', 'reject', 'init'] class TuringMachine(object): def __init__(self, sigma, gamma, delta): self.sigma = sigma self.gamma = gamma self.delta = delta self.state = None self.tape = None self.head_position = None return ...
else: assert(transition[2] == 'right') if self.head_position == len(self.tape) - 1: self.tape.append('#') self.head_position +=1 if verbose: self.print_tape_contents() return def print_tape_contents(self): for...
self.head_position = max(0, self.head_position - 1)
conditional_block
turing.py
required_states = ['accept', 'reject', 'init'] class TuringMachine(object): def __init__(self, sigma, gamma, delta): self.sigma = sigma self.gamma = gamma self.delta = delta self.state = None self.tape = None self.head_position = None return ...
(self): formatted = ''.join(char if i != self.head_position else '[%s]' % char for i, char in enumerate(self.tape)) print(formatted) def run(self, input_string, verbose=False): self.initialize(input_string) while self.state not in ['reject', ...
print_tape_contents
identifier_name
annotate_features.py
from django.core.management.base import BaseCommand, CommandError from django.db import transaction import sys import json from twit.models import User, Tweet, Mention, UserMention from javanlp.models import Sentence, Sentiment from javanlp.util import AnnotationException, annotate_document_with_sentiment class Com...
"""Annotate tweets and load into database.""" help = __doc__ #def add_arguments(self, parser): # import argparse # parser.add_argument('--input', type=argparse.FileType('r'), help="Input file containing a json tweet on each line.") def handle(self, *args, **options): for tweet in Twe...
identifier_body
annotate_features.py
from django.core.management.base import BaseCommand, CommandError from django.db import transaction import sys import json from twit.models import User, Tweet, Mention, UserMention from javanlp.models import Sentence, Sentiment from javanlp.util import AnnotationException, annotate_document_with_sentiment class Com...
except AnnotationException: pass # Couldn't annotate this sentence...
sentence.save() sentiment.sentence = sentence sentiment.save()
conditional_block
annotate_features.py
from django.core.management.base import BaseCommand, CommandError from django.db import transaction import sys import json from twit.models import User, Tweet, Mention, UserMention from javanlp.models import Sentence, Sentiment from javanlp.util import AnnotationException, annotate_document_with_sentiment class Com...
for tweet in Tweet.objects.all(): if Sentence.objects.filter(doc_id = tweet.id).exists(): continue try: with transaction.atomic(): for sentence, sentiment in annotate_document_with_sentiment(tweet.id, tweet.text): sentence.save(...
#def add_arguments(self, parser): # import argparse # parser.add_argument('--input', type=argparse.FileType('r'), help="Input file containing a json tweet on each line.") def handle(self, *args, **options):
random_line_split
annotate_features.py
from django.core.management.base import BaseCommand, CommandError from django.db import transaction import sys import json from twit.models import User, Tweet, Mention, UserMention from javanlp.models import Sentence, Sentiment from javanlp.util import AnnotationException, annotate_document_with_sentiment class
(BaseCommand): """Annotate tweets and load into database.""" help = __doc__ #def add_arguments(self, parser): # import argparse # parser.add_argument('--input', type=argparse.FileType('r'), help="Input file containing a json tweet on each line.") def handle(self, *args, **options): ...
Command
identifier_name
discover.js
import Ember from 'ember'; import moment from 'moment'; import dateFormat from '../utils/date-format'; export default Ember.Controller.extend({ loadingMeta: false, notify: Ember.inject.service(), aggController: Ember.inject.controller('discover.aggregate'), queryParams: ['center', 'obs_date__le', 'obs_date_...
, // Central location to define all acceptable values for aggregate-query-maker // IDs for cities, their display names, and bounds (usually city limits) // City bounding boxes determined via https://www.mapdevelopers.com/geocode_bounding_box.php cities: { default: { // "Cities" named "default" are no...
{ return Ember.copy(this.get('queryParamsHash')); }
identifier_body
discover.js
import Ember from 'ember'; import moment from 'moment'; import dateFormat from '../utils/date-format'; export default Ember.Controller.extend({ loadingMeta: false, notify: Ember.inject.service(), aggController: Ember.inject.controller('discover.aggregate'), queryParams: ['center', 'obs_date__le', 'obs_date_...
// _zoomIn() { // this.set('zoom', true); // const self = this; // Ember.run.next(() => { // self.set('zoom', false); // }); // }, _resetDatePickers() { this.set('override', true); Ember.run.next(() => { this.set('override', false); }); }, _inIndex() { // Thanks:...
{ id: '1000', label: '1 kilometer' }, ]), // ------------- end of central aggregate-query-maker values ---------------//
random_line_split
discover.js
import Ember from 'ember'; import moment from 'moment'; import dateFormat from '../utils/date-format'; export default Ember.Controller.extend({ loadingMeta: false, notify: Ember.inject.service(), aggController: Ember.inject.controller('discover.aggregate'), queryParams: ['center', 'obs_date__le', 'obs_date_...
// Refocus map on user-drawn shape. // if (this.get('location_geom__within')) { // this._zoomIn(); // } }, reset() { if (!this._inIndex()) { this.transitionToRoute('index'); } this._resetParams(); this._resetDatePickers(); }, }, });
{ this.get('aggController').send('submit'); }
conditional_block
discover.js
import Ember from 'ember'; import moment from 'moment'; import dateFormat from '../utils/date-format'; export default Ember.Controller.extend({ loadingMeta: false, notify: Ember.inject.service(), aggController: Ember.inject.controller('discover.aggregate'), queryParams: ['center', 'obs_date__le', 'obs_date_...
() { this.set('override', true); Ember.run.next(() => { this.set('override', false); }); }, _inIndex() { // Thanks: https://gist.github.com/eliotsykes/8954cf64fcd0df16f519 return Ember.getOwner(this).lookup('controller:application').currentPath === 'discover.index'; }, actions: { ...
_resetDatePickers
identifier_name
views.py
from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.views import generic from django.views.generic.edit import FormView, CreateView from django.core.urlresolvers import reverse_lazy from django.core.mail import send_mail from hacks.models import Hackathon, CodeMania, SendR...
def post(self, request, uid): uid = str(request.get_full_path()).split('/')[-1] if RSVPConfirmation.objects.filter(sent_rsvp__uid = uid).count() == 1: return HttpResponseForbidden() else: college = request.POST.get('college', '') status = request.POST.get('status', False) rsvp_obj = SendRSVP.objec...
return render(request, template_name, {'uid': uid})
conditional_block
views.py
from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.views import generic from django.views.generic.edit import FormView, CreateView from django.core.urlresolvers import reverse_lazy from django.core.mail import send_mail from hacks.models import Hackathon, CodeMania, SendR...
(self, request): import uuid emails = request.POST.get('emails', None) emails = emails.replace('\r','') emails = emails.split('\n') plaintext = get_template('rsvp_confirmation_mail.txt') htmly = get_template('rsvp_confirmation_mail.html') for email in emails: if email is not None or email is not ""...
post
identifier_name
views.py
from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.views import generic from django.views.generic.edit import FormView, CreateView from django.core.urlresolvers import reverse_lazy from django.core.mail import send_mail from hacks.models import Hackathon, CodeMania, SendR...
# def post(self, request): # try: # name = request.POST.get('name', None) # email = request.POST.get('email',None ) # phone_number = request.POST.get('phone_number', None) # year = request.POST.get('year', None) # course= request.POST.get('course', None) # branch= request.POST.get('branch', None)...
form = CodeManiaForm template_name = 'codemania.html' return render(request, template_name, {'form':form})
identifier_body
views.py
from django.shortcuts import render from django.http import HttpResponse,JsonResponse from django.views import generic from django.views.generic.edit import FormView, CreateView from django.core.urlresolvers import reverse_lazy from django.core.mail import send_mail from hacks.models import Hackathon, CodeMania, SendR...
def as_view(cls, **initkwargs): view = super(LoginRequiredMixin, cls).as_view(**initkwargs) return login_required(view) class sendRSVP(LoginRequiredMixin, generic.View): def get(self, request): template_name = 'send_rsvp.html' return render(request, template_name, ) def post(self, request): import uuid ...
from django.contrib.auth.decorators import login_required class LoginRequiredMixin(object): @classmethod
random_line_split
hdf5_loading_three_bumps.py
import h5py import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from signals.aux_functions import gaussian_bump import nexa.loading as load from visualization.sensors import visualize_SLM_hdf5 from visualization.sensors import visualize_STDM_hdf5 from visualization.sensor_clusteri...
# Now visualize the SLM and STDM if False: fig = plt.figure() gs = gridspec.GridSpec(2, 2) ax1 = fig.add_subplot(gs[:, 0]) visualize_SLM_hdf5(database, run_name, ax=ax1) ax2 = fig.add_subplot(gs[:, 1]) visualize_STDM_hdf5(database, run_name, nexa_arrangement, ax= ax2) fig.show() p...
fig = plt.figure() gs = gridspec.GridSpec(3, 2) ax1 = fig.add_subplot(gs[0, 0]) ax1.plot(time, gb1) ax2 = fig.add_subplot(gs[1, 0]) ax2.plot(time,gb2) ax3 = fig.add_subplot(gs[2, 0]) ax3.plot(time, gb3) ax4 = fig.add_subplot(gs[:, 1]) visualize_STDM_hdf5(database, run_name, nexa_ar...
conditional_block
hdf5_loading_three_bumps.py
import h5py import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from signals.aux_functions import gaussian_bump import nexa.loading as load from visualization.sensors import visualize_SLM_hdf5 from visualization.sensors import visualize_STDM_hdf5 from visualization.sensor_clusteri...
ax1 = fig.add_subplot(gs[0, 0]) ax1.plot(time, gb1) ax2 = fig.add_subplot(gs[1, 0]) ax2.plot(time,gb2) ax3 = fig.add_subplot(gs[2, 0]) ax3.plot(time, gb3) ax4 = fig.add_subplot(gs[:, 1]) visualize_STDM_hdf5(database, run_name, nexa_arrangement, ax= ax4) plt.show() # Now visua...
if False: fig = plt.figure() gs = gridspec.GridSpec(3, 2)
random_line_split
mapService.js
, longitude : -3.4430839999999753 }, icon : "img/church/blue-outline-church-64.png", iconInverse : "img/church/blank-outline-church-64.png", options : "", title : "L'église", description : "Nous vous donnons rendez-vous à 10h45 pour la célébration qui aura lieu à l'église Saint Jacques à Perros G...
longitude : -3.3538073 }, icon : "img/hotel/blue-outline-hotel-64.png", iconInverse : "img/hotel/blank-outline-hotel-64.png", options : "", distance : "à 600 m de la salle", title : "Les Terrasses de Trestel", description : "<i>Entre Tréguier et Perros-Guirec, en bordure d'une magnifique plage ...
latitude : 48.8189145,
random_line_split
time.rs
// Copyright 2015 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 ...
extern { pub fn mach_absolute_time() -> u64; pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int; } impl SteadyTime { pub fn now() -> SteadyTime { SteadyTime { t: unsafe { mach_absolute_time() }, } } ...
pub struct SteadyTime { t: u64 }
random_line_split
time.rs
// Copyright 2015 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 ...
} } }
{ Duration::seconds(self.t.tv_sec as i64 - 1 - other.t.tv_sec as i64) + Duration::nanoseconds(self.t.tv_nsec as i64 + NSEC_PER_SEC - other.t.tv_nsec as i64) }
conditional_block
time.rs
// Copyright 2015 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 ...
} } #[cfg(not(any(target_os = "macos", target_os = "ios")))] mod inner { use libc; use time::Duration; use ops::Sub; const NSEC_PER_SEC: i64 = 1_000_000_000; pub struct SteadyTime { t: libc::timespec, } // Apparently android provides this in some other library? // Bitrig...
{ let info = info(); let diff = self.t as i64 - other.t as i64; Duration::nanoseconds(diff * info.numer as i64 / info.denom as i64) }
identifier_body
time.rs
// Copyright 2015 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 ...
{ t: u64 } extern { pub fn mach_absolute_time() -> u64; pub fn mach_timebase_info(info: *mut libc::mach_timebase_info) -> libc::c_int; } impl SteadyTime { pub fn now() -> SteadyTime { SteadyTime { t: unsafe { mach_absolute_time() }, ...
SteadyTime
identifier_name
keyframes_rule.rs
Arc::new(lock.wrap( x.read_with(guard).deep_clone_with_lock(lock, guard, params) )) }) .collect(), vendor_prefix: self.vendor_prefix.clone(), source_location: self.source_location.clone(), } ...
/// /// This is used to know when to override the keyframe animation style. pub declared_timing_function: bool, } impl KeyframesStep { #[inline] fn new(percentage: KeyframePercentage, value: KeyframesStepValue, guard: &SharedRwLockReadGuard) -> Self { let declared_timi...
pub value: KeyframesStepValue, /// Wether a animation-timing-function declaration exists in the list of /// declarations.
random_line_split
keyframes_rule.rs
Arc::new(lock.wrap( x.read_with(guard).deep_clone_with_lock(lock, guard, params) )) }) .collect(), vendor_prefix: self.vendor_prefix.clone(), source_location: self.source_location.clone(), } } } /// A numbe...
(&self) -> &[KeyframePercentage] { &self.0 } /// A dummy public function so we can write a unit test for this. pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector { KeyframeSelector(percentages) } /// Parse a keyframe selector from CSS input. p...
percentages
identifier_name
keyframes_rule.rs
))] pub struct KeyframesStep { /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, ...
{ block.extend(iter.parser.declarations.drain(), Importance::Normal); }
conditional_block
keyframes_rule.rs
Arc::new(lock.wrap( x.read_with(guard).deep_clone_with_lock(lock, guard, params) )) }) .collect(), vendor_prefix: self.vendor_prefix.clone(), source_location: self.source_location.clone(), } } } /// A numbe...
} impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && value <= 1.); KeyframePercentage(value) } fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentag...
{ serialize_percentage(self.0, dest) }
identifier_body
statistic-gadget.component.ts
import {ChangeDetectorRef, Component} from '@angular/core'; import {RuntimeService} from '../../services/runtime.service'; import {GadgetInstanceService} from '../../grid/grid.service'; import {EndPointService} from '../../configuration/tab-endpoint/endpoint.service'; import {GadgetPropertyService} from '../_common/gad...
resource: string; constructor(protected _statisticService: StatisticService, protected _procMonRuntimeService: RuntimeService, protected _gadgetInstanceService: GadgetInstanceService, protected _propertyService: GadgetPropertyService, protected _e...
// runtime document subscription data: any;
random_line_split
statistic-gadget.component.ts
import {ChangeDetectorRef, Component} from '@angular/core'; import {RuntimeService} from '../../services/runtime.service'; import {GadgetInstanceService} from '../../grid/grid.service'; import {EndPointService} from '../../configuration/tab-endpoint/endpoint.service'; import {GadgetPropertyService} from '../_common/gad...
if (updatedPropsObject.hasOwnProperty(prop)) { if (prop === propertyPage.properties[x].key) { propertyPage.properties[x].value = updatedPropsObject[prop]; } } } } }); ...
{ /** * todo * A similar operation exists on the procmman-config-service * whenever the property page form is saved, the in memory board model * is updated as well as the gadget instance properties * which is what the code below does. This can be eliminated with...
identifier_body
statistic-gadget.component.ts
import {ChangeDetectorRef, Component} from '@angular/core'; import {RuntimeService} from '../../services/runtime.service'; import {GadgetInstanceService} from '../../grid/grid.service'; import {EndPointService} from '../../configuration/tab-endpoint/endpoint.service'; import {GadgetPropertyService} from '../_common/gad...
(data: any[]) { this._statisticService.get(this.resource).subscribe(data => { this.data = data; }, error => this.handleError(error)); } public updateProperties(updatedProperties: any) { /** * todo * A similar operation exists on the p...
updateData
identifier_name
statistic-gadget.component.ts
import {ChangeDetectorRef, Component} from '@angular/core'; import {RuntimeService} from '../../services/runtime.service'; import {GadgetInstanceService} from '../../grid/grid.service'; import {EndPointService} from '../../configuration/tab-endpoint/endpoint.service'; import {GadgetPropertyService} from '../_common/gad...
}); this.resource = updatedPropsObject.resource; this.title = updatedPropsObject.title; this.setEndPoint(updatedPropsObject.endpoint); this.updateData(null); } }
{ for (const prop in updatedPropsObject) { if (updatedPropsObject.hasOwnProperty(prop)) { if (prop === propertyPage.properties[x].key) { propertyPage.properties[x].value = updatedPropsObject[prop]; } ...
conditional_block
cppu.py
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- # # This file is part of the LibreOffice project. # # 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/. # ...
(self): if self.count == self.size: raise StopIteration count = self.count self.count = self.count + 1 elem = self.item.dereference() self.item = self.item + 1 return ('[%d]' % count, elem) def __init__(self, typename, value):...
__next__
identifier_name
cppu.py
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- # # This file is part of the LibreOffice project. # # 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/. # ...
def display_hint(self): if self.value['_pSequence']: return 'array' else: return None class UnoTypePrinter(object): '''Prints UNO Type''' def __init__(self, typename, value): self.value = value self.typename = typename.replace('com::sun::star::', '...
return None
conditional_block
cppu.py
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- # # This file is part of the LibreOffice project. # # 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/. # ...
class UnoReferencePrinter(object): '''Prints reference to a UNO interface''' def __init__(self, typename, value): self.value = value self.typename = typename.replace('com::sun::star::', '') def to_string(self): iface = self.value['_pInterface'] if iface: try: ...
'''Prints UNO any''' def __init__(self, typename, value): self.value = value self.typename = typename.replace('com::sun::star::', '') def to_string(self): type_desc = self.value['pType'] assert type_desc type = make_uno_type(type_desc.dereference()) assert type ...
identifier_body
cppu.py
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- # # This file is part of the LibreOffice project. # # 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/. # ...
def build_pretty_printers(): global printer printer = printing.Printer("libreoffice/cppu") # basic UNO stuff printer.add('_uno_Any', UnoAnyPrinter) printer.add('com::sun::star::uno::Any', UnoAnyPrinter) printer.add('com::sun::star::uno::Reference', UnoReferencePrinter) printer.add('com::su...
return '%s@%s' % (self.typename, self.value.address) printer = None
random_line_split
exceptions.py
""" yubistack.exceptions ~~~~~~~~~~~~~~~~~~~~ List all custom exceptions here """ STATUS_CODES = { # YKAuth 'BAD_PASSWORD': 'Invalid password', 'DISABLED_TOKEN': 'Token is disabled', 'UNKNOWN_USER': 'Unknown user', 'INVALID_TOKEN': 'Token is not associated with user', # YKVal 'BACKEND_ERR...
return message class YKAuthError(YubistackError): """ Error returned by the Client class """ NAME = 'Authentication error' class YKValError(YubistackError): """ Error returned by the Validator class """ NAME = 'Validation error' class YKSyncError(YubistackError): """ Error returned by th...
message += ': %s' % self.args[1]
conditional_block
exceptions.py
""" yubistack.exceptions ~~~~~~~~~~~~~~~~~~~~ List all custom exceptions here """ STATUS_CODES = { # YKAuth 'BAD_PASSWORD': 'Invalid password', 'DISABLED_TOKEN': 'Token is disabled', 'UNKNOWN_USER': 'Unknown user', 'INVALID_TOKEN': 'Token is not associated with user', # YKVal 'BACKEND_ERR...
'OPERATION_NOT_ALLOWED': 'The request is now allowed', 'REPLAYED_OTP': 'Replayed OTP', 'REPLAYED_REQUEST': 'Server has seen the OTP/Nonce combination before', # YKKSM 'CORRUPT_OTP': 'Corrupt OTP', 'MISSING_OTP': 'No OTP provided', 'UNKNOWN_TOKEN': 'Unknown yubikey', } class YubistackError(E...
random_line_split
exceptions.py
""" yubistack.exceptions ~~~~~~~~~~~~~~~~~~~~ List all custom exceptions here """ STATUS_CODES = { # YKAuth 'BAD_PASSWORD': 'Invalid password', 'DISABLED_TOKEN': 'Token is disabled', 'UNKNOWN_USER': 'Unknown user', 'INVALID_TOKEN': 'Token is not associated with user', # YKVal 'BACKEND_ERR...
(YubistackError): """ Error returned by the Sync class """ NAME = 'Sync error' class YKKSMError(YubistackError): """ Error returned by the Decryptor class """ NAME = 'Decryption error'
YKSyncError
identifier_name
exceptions.py
""" yubistack.exceptions ~~~~~~~~~~~~~~~~~~~~ List all custom exceptions here """ STATUS_CODES = { # YKAuth 'BAD_PASSWORD': 'Invalid password', 'DISABLED_TOKEN': 'Token is disabled', 'UNKNOWN_USER': 'Unknown user', 'INVALID_TOKEN': 'Token is not associated with user', # YKVal 'BACKEND_ERR...
def __str__(self): message = STATUS_CODES[self.error_code] if len(self.args) == 2: message += ': %s' % self.args[1] return message class YKAuthError(YubistackError): """ Error returned by the Client class """ NAME = 'Authentication error' class YKValError(YubistackErr...
super(YubistackError, self).__init__(*args) self.error_code = self.args[0]
identifier_body
train.py
_RESULTS_DIR from ray.tune.resources import resources_to_json from ray.tune.tune import run_experiments from ray.tune.schedulers import create_scheduler from ray.rllib.utils.deprecation import deprecation_warning from ray.rllib.utils.framework import try_import_tf, try_import_torch try: class_name = get_ipython()....
main
identifier_name
train.py
une.config_parser import make_parser from ray.tune.progress_reporter import CLIReporter, JupyterNotebookReporter from ray.tune.result import DEFAULT_RESULTS_DIR from ray.tune.resources import resources_to_json from ray.tune.tune import run_experiments from ray.tune.schedulers import create_scheduler from ray.rllib.util...
if IS_NOTEBOOK: progress_reporter = JupyterNotebookReporter( overwrite=verbose >= 3, print_intermediate_tables=verbose >= 1 ) else: progress_reporter = CLIReporter(print_intermediate_tables=verbose >= 1) run_experiments( experiments, scheduler=create_sch...
num_gpus=args.ray_num_gpus, local_mode=args.local_mode, )
random_line_split
train.py
une.config_parser import make_parser from ray.tune.progress_reporter import CLIReporter, JupyterNotebookReporter from ray.tune.result import DEFAULT_RESULTS_DIR from ray.tune.resources import resources_to_json from ray.tune.tune import run_experiments from ray.tune.schedulers import create_scheduler from ray.rllib.util...
"--no-ray-ui", action="store_true", help="Deprecated! Ray UI is disabled by default now. " "Use `--ray-ui` to enable.", ) parser.add_argument( "--local-mode", action="store_true", help="Run ray in local mode for easier debugging.", ) parser.add_arg...
parser = make_parser( parser_creator=parser_creator, formatter_class=argparse.RawDescriptionHelpFormatter, description="Train a reinforcement learning agent.", epilog=EXAMPLE_USAGE, ) # See also the base parser definition in ray/tune/config_parser.py parser.add_argument( ...
identifier_body
train.py
une.config_parser import make_parser from ray.tune.progress_reporter import CLIReporter, JupyterNotebookReporter from ray.tune.result import DEFAULT_RESULTS_DIR from ray.tune.resources import resources_to_json from ray.tune.tune import run_experiments from ray.tune.schedulers import create_scheduler from ray.rllib.util...
if args.torch: deprecation_warning("--torch", "--framework=torch") exp["config"]["framework"] = "torch" elif args.eager: deprecation_warning("--eager", "--framework=[tf2|tfe]") exp["config"]["framework"] = "tfe" elif args.framework is not None: ...
parser.error("the following arguments are required: --env")
conditional_block
setup.js
jQuery.sap.registerModulePath("oui5lib", "webapp"); var oui5lib = {}; oui5lib.namespace = function(string) { var object = this; var levels = string.split("."); for (var i = 0, l = levels.length; i < l; i++) { if (typeof object[levels[i]] === "undefined") { object[levels[i]] = {}; ...
} } }; xhr.send();
random_line_split
setup.js
jQuery.sap.registerModulePath("oui5lib", "webapp"); var oui5lib = {}; oui5lib.namespace = function(string) { var object = this; var levels = string.split("."); for (var i = 0, l = levels.length; i < l; i++) { if (typeof object[levels[i]] === "undefined") { object[levels[i]] = {}; ...
}; xhr.send();
{ if (xhr.status === 200 || xhr.status === 0) { try { const configData = JSON.parse(xhr.responseText); oui5lib.config = configData; } catch (e) { throw new Error("Not valid JSON"); } } }
conditional_block
vyatta-filechooser.js
var FileChooser = function(config)
// Setup a variable for the current directory this.current_directory; /* ---- Begin side_navbar tree --- */ this.tree = new Ext.tree.TreePanel( { region: 'west', width: 150, minSize: 150, maxSize: 250, animate: true, loader: new Ext.tree.Tr...
{
random_line_split
vyatta-filechooser.js
var FileChooser = function(config) { // Setup a variable for the current directory this.current_directory; /* ---- Begin side_navbar tree --- */ this.tree = new Ext.tree.TreePanel( { region: 'west', width: 150, minSize: 150, maxSize: 250, animate:...
{ var chooser = new FileChooser({width: 500, height:400}); chooser.show(fieldName, function(el, data) { win.document.getElementById(el).value = data; }); }
identifier_body
vyatta-filechooser.js
var FileChooser = function(config) { // Setup a variable for the current directory this.current_directory; /* ---- Begin side_navbar tree --- */ this.tree = new Ext.tree.TreePanel( { region: 'west', width: 150, minSize: 150, maxSize: 250, animate:...
(fieldName, url, win) { var chooser = new FileChooser({width: 500, height:400}); chooser.show(fieldName, function(el, data) { win.document.getElementById(el).value = data; }); }
FileBrowser
identifier_name
NoteTwoTone.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime")...
exports.default = _default;
opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M4 4c-1.1 0-2 .9-2 2v12.01c0 1.1.9 1.99 2 1.99h16c1.1 0 2-.9 2-2v-8l-6-6H4zm16 14.01H4V6h11v5h5v7.01z" }, "1")], 'NoteTwoTone');
random_line_split
unit_graph.rs
use std::collections::{HashMap, VecDeque, HashSet}; use nom::types::CompleteStr; use petgraph::graph::{UnGraph, NodeIndex, DefaultIx}; use bigdecimal::BigDecimal; use num_traits::One; use crate::canonical::CanonicalUnit; use crate::ast::*; use crate::ir::ConversionRatio; pub type UnitID = usize; #[derive(Debug, Clo...
/// Creates the given unit if it does not exist yet /// /// If it does exist, this function will return an error pub fn insert_unit(&mut self, name: UnitName<'a>, span: Span<'a>) -> Result<UnitID, DuplicateUnit<'a>> { if self.unit_ids.contains_key(&name) { return Err(DuplicateUnit(...
{ match self.units.get(unit) { Some(&(ref name, _)) => name, None => unreachable!("Looked up an ID that did not exist"), } }
identifier_body
unit_graph.rs
use std::collections::{HashMap, VecDeque, HashSet}; use nom::types::CompleteStr; use petgraph::graph::{UnGraph, NodeIndex, DefaultIx}; use bigdecimal::BigDecimal; use num_traits::One; use crate::canonical::CanonicalUnit; use crate::ast::*; use crate::ir::ConversionRatio; pub type UnitID = usize; #[derive(Debug, Clo...
let node = CanonicalUnit::from(id); let graph_id = self.conversions.add_node(node.clone()); assert!(self.graph_ids.insert(node, graph_id).is_none(), "bug: failed to detect duplicate declaration"); Ok(id) } /// Adds the given conversion ratio to the graph pub fn...
"bug: failed to detect duplicate declaration"); self.units.push((name, span));
random_line_split
unit_graph.rs
use std::collections::{HashMap, VecDeque, HashSet}; use nom::types::CompleteStr; use petgraph::graph::{UnGraph, NodeIndex, DefaultIx}; use bigdecimal::BigDecimal; use num_traits::One; use crate::canonical::CanonicalUnit; use crate::ast::*; use crate::ir::ConversionRatio; pub type UnitID = usize; #[derive(Debug, Clo...
else { unreachable!(); } } factor } } #[derive(Debug, Clone)] pub struct UnitGraph<'a> { unit_ids: HashMap<UnitName<'a>, UnitID>, units: Vec<(UnitName<'a>, Span<'a>)>, graph_ids: HashMap<CanonicalUnit, NodeIndex<DefaultIx>>, conversions: UnG...
{ factor *= ratio.left.value / ratio.right.value; current = ratio.left.unit; }
conditional_block
unit_graph.rs
use std::collections::{HashMap, VecDeque, HashSet}; use nom::types::CompleteStr; use petgraph::graph::{UnGraph, NodeIndex, DefaultIx}; use bigdecimal::BigDecimal; use num_traits::One; use crate::canonical::CanonicalUnit; use crate::ast::*; use crate::ir::ConversionRatio; pub type UnitID = usize; #[derive(Debug, Clo...
{ start: CanonicalUnit, end: CanonicalUnit, ratio_path: Vec<ConversionRatio>, } impl ConversionPath { /// Reduces the path into the factor that transforms start to end pub fn conversion_factor(self) -> BigDecimal { let mut factor = BigDecimal::one(); let mut current = self.start; ...
ConversionPath
identifier_name
utils.py
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
(lifetime_dict): for key, value in lifetime_dict.items(): if key not in lifetime_keys: message = _( "Lifetime Dictionary KeyError: " "Reason-Invalid unit key : " "'%(key)s' not in %(supported_key)s ") % { 'key': key, 'supported...
validate_lifetime_dict
identifier_name
utils.py
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
def dpd_help(policy): dpd = _(" %s Dead Peer Detection attributes." " 'action'-hold,clear,disabled,restart,restart-by-peer." " 'interval' and 'timeout' are non negative integers. " " 'interval' should be less than 'timeout' value. " " 'action', default:hold 'interv...
lifetime = _("%s lifetime attributes. " "'units'-seconds, default:seconds. " "'value'-non negative integer, default:3600.") % policy return lifetime
identifier_body
utils.py
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
# """VPN Utilities and helper functions.""" from neutronclient.common import exceptions from neutronclient.i18n import _ dpd_supported_actions = ['hold', 'clear', 'restart', 'restart-by-peer', 'disabled'] dpd_supported_keys = ['action', 'interval', 'timeout'] lifetime_keys = ['units', 'va...
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # @author: Swaminathan Vasudevan, Hewlett-Packard.
random_line_split
utils.py
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P. # 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...
message = _( "DPD Dictionary ValueError: " "Reason-Invalid positive integer value: " "'%(key)s' = %(value)s ") % { 'key': key, 'value': value} raise exceptions.CommandError(message) else: ...
if key not in dpd_supported_keys: message = _( "DPD Dictionary KeyError: " "Reason-Invalid DPD key : " "'%(key)s' not in %(supported_key)s ") % { 'key': key, 'supported_key': dpd_supported_keys} raise exceptions.CommandError(mes...
conditional_block
errors.rs
// Copyright 2016 Jonas mg // See the 'AUTHORS' file at the top-level directory for a full list of authors. // // 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 s...
} impl fmt::Display for AsciiError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { AsciiError::ControlChar(pos) => write!(f, "{} at position {}", self.description(), pos), AsciiError::NonAscii(ch) => write!(f, "{} ({})", self.description(), ch), } ...
{ match *self { AsciiError::ControlChar(_) => "contain ASCII control character", AsciiError::NonAscii(_) => "contain non US-ASCII character", } }
identifier_body
errors.rs
// Copyright 2016 Jonas mg // See the 'AUTHORS' file at the top-level directory for a full list of authors. // // 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 s...
(&self) -> &str { match *self { AsciiError::ControlChar(_) => "contain ASCII control character", AsciiError::NonAscii(_) => "contain non US-ASCII character", } } } impl fmt::Display for AsciiError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *se...
description
identifier_name