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 |
|---|---|---|---|---|
resource-destruct.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 my_total = &Cell::new(10);
{ let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); }
println!("my_total = {}", my_total.get());
assert_eq!(my_total.get(), 9);
}
| main | identifier_name |
resource-destruct.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 ... |
}
fn shrinky_pointer(i: &Cell<isize>) -> shrinky_pointer {
shrinky_pointer {
i: i
}
}
pub fn main() {
let my_total = &Cell::new(10);
{ let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); }
println!("my_total = {}", my_total.get());
assert_eq!(my_total.get(), 9);
}
| { return self.i.get(); } | identifier_body |
resource-destruct.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | random_line_split | |
conf.py | # -*- coding: utf-8 -*-
#
# powerschool_apps documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration valu... | # The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of th... | # html_theme_path = []
| random_line_split |
workqueue.js | /**
* This file is part of Superdesk.
*
* Copyright 2015 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
W... | }
multiEdit.items = _.without(multiEdit.items, _.find(multiEdit.items, {article: item._id}));
if (multiEdit.items.length === 0){
$scope.redirectOnCloseMulti();
}
};
$scope.openMulti = function() {
$scope.isMultiedit = true;
multiEdit.open();
};
... | if (authoringWorkspace.item && item._id === authoringWorkspace.item._id){
authoringWorkspace.close(); | random_line_split |
workqueue.js | /**
* This file is part of Superdesk.
*
* Copyright 2015 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
W... | (session, api) {
this.items = [];
/**
* Get all items locked by current user
*/
this.fetch = function() {
return session.getIdentity()
.then(angular.bind(this, function(identity) {
return api.query('archive', {source: {filter: {term: {lock_user: identity._id}}... | WorkqueueService | identifier_name |
workqueue.js | /**
* This file is part of Superdesk.
*
* Copyright 2015 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
W... |
};
}
WorkqueueCtrl.$inject = ['$scope', '$route', 'workqueue', 'authoringWorkspace', 'multiEdit', 'superdesk', 'lock', '$location'];
function WorkqueueCtrl($scope, $route, workqueue, authoringWorkspace, multiEdit, superdesk, lock, $location) {
$scope.active = null;
$scope.workqueue = workqueue;
$scop... | {
return api.find('archive', itemId).then(function(item) {
return angular.extend(old, item);
});
} | conditional_block |
workqueue.js | /**
* This file is part of Superdesk.
*
* Copyright 2015 Sourcefabric z.u. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code, or
* at https://www.sourcefabric.org/superdesk/license
*/
(function() {
'use strict';
W... |
angular.module('superdesk.authoring.workqueue', [
'superdesk.activity',
'superdesk.notification',
'superdesk.authoring.multiedit'
])
.service('workqueue', WorkqueueService)
.controller('Workqueue', WorkqueueCtrl)
.directive('sdWorkqueue', WorkqueueListDirective)
.directive('sdDashboardArti... | {
return {
templateUrl: 'scripts/superdesk-authoring/views/dashboard-articles.html',
controller: 'Workqueue'
};
} | identifier_body |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... |
}
}
| {
use graphics::*;
gl.draw(args.viewport(), |c, gl| {
let transform = c.transform.trans(0.0, 100.0);
clear(color::WHITE, gl);
render_text(&mut face, gl, transform, "Hello Piston!");
});
} | conditional_block |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... |
gl.draw(args.viewport(), |c, gl| {
let transform = c.transform.trans(0.0, 100.0);
clear(color::WHITE, gl);
render_text(&mut face, gl, transform, "Hello Piston!");
});
}
}
}
| {
let opengl = OpenGL::V3_2;
let window: Sdl2Window =
WindowSettings::new("piston-example-freetype", [300, 300])
.exit_on_esc(true)
.opengl(opengl)
.into();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let freetype = ft... | identifier_body |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... | (face: &mut ft::Face, gl: &mut GlGraphics, t: Matrix2d, text: &str) {
use graphics::*;
let mut x = 10;
let mut y = 0;
for ch in text.chars() {
face.load_char(ch as usize, ft::face::RENDER).unwrap();
let g = face.glyph();
let bitmap = g.bitmap();
let texture = Texture::f... | render_text | identifier_name |
main.rs | extern crate graphics;
extern crate freetype as ft;
extern crate sdl2_window;
extern crate opengl_graphics;
extern crate piston;
extern crate find_folder;
use sdl2_window::Sdl2Window;
use opengl_graphics::{ GlGraphics, Texture, OpenGL };
use graphics::math::Matrix2d;
use piston::window::WindowSettings;
use piston::eve... | }
}
} | random_line_split | |
bgp_daemon.py | under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import sys
from logging import Logger
import logging.config
# impor... | else:
logging.config.fileConfig(
options.logFile, disable_existing_loggers=False)
if action == "start":
logging.root.name = "Main"
logging.info("Starting...")
else: # stop
logging.root.name = "Stopper"
logging.info("Signal daemon to stop")
catchAllL... | usage = "usage: %prog [options] (see --help)"
parser = OptionParser(usage)
parser.add_option("--config-file", dest="configFile",
help="Set BGP component configuration file path",
default="/etc/bagpipe-bgp/bgp.conf")
parser.add_option("--log-file", dest="logFile",... | identifier_body |
bgp_daemon.py | under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import sys
from logging import Logger
import logging.config
# impor... | (dpConfigs, bgpConfig, isCleaningUp=False):
drivers = dict()
for vpnType in dpConfigs.iterkeys():
dpConfig = dpConfigs[vpnType]
if 'dataplane_driver' not in dpConfig:
logging.error(
"no dataplane_driver set for %s (%s)", vpnType, dpConfig)
driverName = dpCon... | findDataplaneDrivers | identifier_name |
bgp_daemon.py | under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os.path
import sys
from logging import Logger
import logging.config
# impor... |
class BgpDaemon(LookingGlass):
def __init__(self, catchAllLGLogHandler, **kwargs):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/null'
self.stderr_path = '/dev/null'
self.pidfile_path = '/var/run/bagpipe-bgp/bagpipe-bgp.pid'
self.pidfile_timeout = 5
loggi... | "Could not initiate dataplane driver for %s with %s (%s)",
vpnType, tentativeClassName, e)
return drivers | random_line_split |
bgp_daemon.py |
from bagpipe.bgp.common.looking_glass import LookingGlass, \
LookingGlassLogHandler
from bagpipe.bgp.engine.bgp_manager import Manager
from bagpipe.bgp.rest_api import RESTAPI
from bagpipe.bgp.vpn import VPNManager
def findDataplaneDrivers(dpConfigs, bgpConfig, isCleaningUp=False):
drivers = dict()
fo... | print "no logging configuration file at %s" % options.logFile
logging.basicConfig() | conditional_block | |
navigatorinfo.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::DOMString;
use util::opts;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}... | () -> bool {
false
}
pub fn AppName() -> DOMString {
DOMString::from("Netscape") // Like Gecko/Webkit
}
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn Platform() -> DOMString {
DOMString::from("Win32")
}
#[cfg(any(target_os = "android", target_o... | TaintEnabled | identifier_name |
navigatorinfo.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::DOMString;
use util::opts;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}... |
pub fn UserAgent() -> DOMString {
DOMString::from(&*opts::get().user_agent)
}
pub fn AppVersion() -> DOMString {
DOMString::from("4.0")
}
pub fn Language() -> DOMString {
DOMString::from("en-US")
}
| {
DOMString::from("Mac")
} | identifier_body |
navigatorinfo.rs | use util::opts;
pub fn Product() -> DOMString {
DOMString::from("Gecko")
}
pub fn TaintEnabled() -> bool {
false
}
pub fn AppName() -> DOMString {
DOMString::from("Netscape") // Like Gecko/Webkit
}
pub fn AppCodeName() -> DOMString {
DOMString::from("Mozilla")
}
#[cfg(target_os = "windows")]
pub fn... | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::str::DOMString; | random_line_split | |
journey.js | /**
* maas.js - Client for maas-server
* Copyright (C) 2015 haphut <haphut@gmail.com>
*
* This file is part of maas.js.
*
* maas.js is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version... | *
* You should have received a copy of the GNU Affero General Public License
* along with maas.js. If not, see <http://www.gnu.org/licenses/>.
*/
import uuid from 'node-uuid';
const createJourneyId = uuid.v4;
export {createJourneyId}; | random_line_split | |
dotplot.src.js | /**
* @license Highcharts JS v7.1.3 (2019-08-14)
*
* Dot plot series type for Highcharts
*
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.ex... |
itemY = point.y;
yTop = pick(point.stackY, point.y);
size = Math.min(point.pointWidth, series.yAxis.transA - itemPaddingTranslated);
for (yPos = yTop; yPos > yTop - point.y; yPos--) {
x = point.b... | {
point.graphic = renderer.g('point').add(series.group);
} | conditional_block |
dotplot.src.js | /**
* @license Highcharts JS v7.1.3 (2019-08-14)
*
* Dot plot series type for Highcharts
*
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.ex... | .add(point.graphic);
}
graphics[itemY].isActive = true;
itemY--;
}
}
objectEach(graphics, function (graphic, key) {
... | random_line_split | |
dotplot.src.js | /**
* @license Highcharts JS v7.1.3 (2019-08-14)
*
* Dot plot series type for Highcharts
*
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.ex... |
_registerModule(_modules, 'modules/dotplot.src.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js']], function (H, U) {
/* *
*
* (c) 2009-2019 Torstein Honsi
*
* Dot plot series type for Highcharts
*
* License: www.highcharts.com/licens... | {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
} | identifier_body |
dotplot.src.js | /**
* @license Highcharts JS v7.1.3 (2019-08-14)
*
* Dot plot series type for Highcharts
*
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.ex... | (obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'modules/dotplot.src.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js']], function (H, U) {
/* *
*
* (c) 2009-2019 Torst... | _registerModule | identifier_name |
ez_setup.py | 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_egg(egg, archive_filename, to_dir):
"""Build Setuptools egg."""
with archive_context(archive_f... | return version | conditional_block | |
ez_setup.py | # installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_e... | if platform.system() != 'Windows':
return False
cmd = ['powershell', '-Command', 'echo test']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_f... | def has_powershell():
"""Determine if Powershell is available.""" | random_line_split |
ez_setup.py | ):
raise IOError('Could not build the egg.')
class ContextualZipFile(zipfile.ZipFile):
"""Supplement ZipFile class to support context manager for Python 2.6."""
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __new__(cls, *args,... | """
Build the arguments to 'python setup.py install' on the setuptools package.
Returns list of command line arguments.
"""
return ['--user'] if options.user_install else [] | identifier_body | |
ez_setup.py | # installing
log.warn('Installing Setuptools')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_e... | (url, target):
"""Use Python to download the file, without connection authentication."""
src = urlopen(url)
try:
# Read all the data in one block.
data = src.read()
finally:
src.close()
# Write all the data in one block to avoid creating a partial file.
with open(target,... | download_file_insecure | identifier_name |
grs-import-sqlid.py | #!/bin/python
# coding: utf-8
import argparse
import sys
import signal
import traceback
import datetime
import lglass.object
import lglass_sql.nic
def objects(lines):
|
argparser = argparse.ArgumentParser()
argparser.add_argument("--schema", "-s")
argparser.add_argument("--encoding", "-e", default="iso-8859-15")
argparser.add_argument("database")
args = argparser.parse_args()
database = lglass_sql.nic.NicDatabase(args.database, schema=args.schema)
if hasattr(database, "session"):... | obj = []
for line in lines:
if isinstance(line, bytes):
line = line.decode("iso-8859-15")
if not line.strip() and obj:
yield lglass.object.parse_object(obj)
obj = []
elif line[0] in {'%', '#'} or not line.strip():
continue
else:
... | identifier_body |
grs-import-sqlid.py | #!/bin/python
# coding: utf-8
import argparse
import sys
import signal
import traceback
import datetime
import lglass.object
import lglass_sql.nic
def objects(lines):
obj = []
for line in lines:
if isinstance(line, bytes):
line = line.decode("iso-8859-15")
if not line.strip() and... |
else:
session = database
print("Collecting local objects...", end='', flush=True)
current_objects = set(session.all_ids())
print(" Done.")
stats = dict(created=0,
updated=0,
deleted=0,
ignored=0,
start=datetime.datetime.now())
def report():
global stats
global current_obje... | session = database.session() | conditional_block |
grs-import-sqlid.py | #!/bin/python
# coding: utf-8
import argparse
import sys
import signal
import traceback
import datetime
import lglass.object
import lglass_sql.nic
def objects(lines):
obj = []
for line in lines:
if isinstance(line, bytes):
line = line.decode("iso-8859-15")
if not line.strip() and... | ():
global stats
global current_objects
print("Created {} / Updated {} / Deleted {} / "
"Ignored {} objects in {}".format(stats["created"],
stats["updated"],
stats["deleted"],
stats["ignored"],
datetime.datetime.now() - stats["start... | report | identifier_name |
grs-import-sqlid.py | #!/bin/python
# coding: utf-8
import argparse
import sys
import signal
import traceback
import datetime
import lglass.object
import lglass_sql.nic
def objects(lines):
obj = []
for line in lines:
if isinstance(line, bytes):
line = line.decode("iso-8859-15")
if not line.strip() and... |
database = lglass_sql.nic.NicDatabase(args.database, schema=args.schema)
if hasattr(database, "session"):
session = database.session()
else:
session = database
print("Collecting local objects...", end='', flush=True)
current_objects = set(session.all_ids())
print(" Done.")
stats = dict(created=0,
upd... | args = argparser.parse_args() | random_line_split |
admin.py | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin
except ImportErro... | (TabbedDjangoJqueryTranslationAdmin if modeltranslation() else admin.ModelAdmin):
"""
Customize PageHelp model for admin area.
"""
list_display = ["page", "title", ]
search_fields = ["title", ]
list_filter = ["page", ]
form = PageHelpAdminForm
if modeltranslation():
# registering tra... | PageHelpAdmin | identifier_name |
admin.py | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin
except ImportErro... |
if modeltranslation():
# registering translation options
translator.register(PageHelp, PageHelpTranslationOptions)
# registering admin custom classes
admin.site.register(PageHelp, PageHelpAdmin)
| """
Customize PageHelp model for admin area.
"""
list_display = ["page", "title", ]
search_fields = ["title", ]
list_filter = ["page", ]
form = PageHelpAdminForm | identifier_body |
admin.py | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin
except ImportErro... | """
Customize PageHelp model for admin area.
"""
list_display = ["page", "title", ]
search_fields = ["title", ]
list_filter = ["page", ]
form = PageHelpAdminForm
if modeltranslation():
# registering translation options
translator.register(PageHelp, PageHelpTranslationOptions)
#... | random_line_split | |
admin.py | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin
except ImportErro... |
# registering admin custom classes
admin.site.register(PageHelp, PageHelpAdmin)
| translator.register(PageHelp, PageHelpTranslationOptions) | conditional_block |
regex.py | import re
romanNumeralRegex = re.compile( "(?:.*\s+\(?)(([(?=[mclxvi])m*(c[md]|d?c*)(x[cl]|l?x*)(i[xv]|v?i*))(?:\.\s.*)", re.IGNORECASE )
romanNumeralChapterVerseRegex = re.compile( "(?:.*\s+\(?)(([(?=[mdclxvi])m*(c[md]|d?c*)(x[cl]|l?x*)(i[xv]|v?i*)(\.\s[0123456789]?[0123456789]))(?:.*)", re.IGNORECASE )
def regexMat... |
def regexFindAllRomanNumeralChapterVerse( value ):
return romanNumeralChapterVerseRegex.findall( value )
| return romanNumeralRegex.findall( value ) | identifier_body |
regex.py | import re
romanNumeralRegex = re.compile( "(?:.*\s+\(?)(([(?=[mclxvi])m*(c[md]|d?c*)(x[cl]|l?x*)(i[xv]|v?i*))(?:\.\s.*)", re.IGNORECASE )
romanNumeralChapterVerseRegex = re.compile( "(?:.*\s+\(?)(([(?=[mdclxvi])m*(c[md]|d?c*)(x[cl]|l?x*)(i[xv]|v?i*)(\.\s[0123456789]?[0123456789]))(?:.*)", re.IGNORECASE )
def regexMat... |
def regexMatchesRomanNumeralChapterVerse( value ):
return romanNumeralChapterVerseRegex.match( value ) != None
def regexFindAllRomanNumeral( value ):
return romanNumeralRegex.findall( value )
def regexFindAllRomanNumeralChapterVerse( value ):
return romanNumeralChapterVerseRegex.findall( value ) | return romanNumeralRegex.match( value ) != None | random_line_split |
regex.py | import re
romanNumeralRegex = re.compile( "(?:.*\s+\(?)(([(?=[mclxvi])m*(c[md]|d?c*)(x[cl]|l?x*)(i[xv]|v?i*))(?:\.\s.*)", re.IGNORECASE )
romanNumeralChapterVerseRegex = re.compile( "(?:.*\s+\(?)(([(?=[mdclxvi])m*(c[md]|d?c*)(x[cl]|l?x*)(i[xv]|v?i*)(\.\s[0123456789]?[0123456789]))(?:.*)", re.IGNORECASE )
def regexMat... | ( value ):
return romanNumeralRegex.findall( value )
def regexFindAllRomanNumeralChapterVerse( value ):
return romanNumeralChapterVerseRegex.findall( value )
| regexFindAllRomanNumeral | identifier_name |
global.ts | // tslint:disable:no-var-keyword prefer-const
import { Store } from '../store';
import { Settings } from '../settings';
import { Trie } from '../trie';
import { Dictionary } from '../dict';
import { Game, GameJSON } from '../game';
import { Stats, Data } from '../stats';
const STORE = new Store('db', 'store');
const D... | for (const h of global.HISTORY) global.PLAYED.add(h.seed);
},
},
}; | PLAYED: async () => {
if (global.PLAYED) return;
await global.LOADED.HISTORY;
global.PLAYED = new Set(); | random_line_split |
global.ts | // tslint:disable:no-var-keyword prefer-const
import { Store } from '../store';
import { Settings } from '../settings';
import { Trie } from '../trie';
import { Dictionary } from '../dict';
import { Game, GameJSON } from '../game';
import { Stats, Data } from '../stats';
const STORE = new Store('db', 'store');
const D... |
},
PLAYED: async () => {
if (global.PLAYED) return;
await global.LOADED.HISTORY;
global.PLAYED = new Set();
for (const h of global.HISTORY) global.PLAYED.add(h.seed);
},
},
};
| {
const game = Game.fromJSON(global.HISTORY[i], global.TRIE, global.DICT, global.STATS);
const played = new Set<string>();
for (const w in game.played) {
if (game.played[w] > 0) played.add(w);
}
global.GAMES.push([game.possible, played]);
} | conditional_block |
format.rs | use super::{
Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10,
EventFormatSerializerV03, EventFormatSerializerV10,
};
use crate::event::{AttributesReader, ExtensionValue};
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use ... |
pub fn parse_data_string<E: serde::de::Error>(v: Value) -> Result<String, E> {
parse_field!(v, String, E)
}
pub fn parse_data_base64<E: serde::de::Error>(v: Value) -> Result<Vec<u8>, E> {
parse_field!(v, String, E).and_then(|s| {
base64::decode(&s).map_err(|e| E::custom(format_args!("decode error `{}... | {
Value::deserialize(v.into_deserializer()).map_err(E::custom)
} | identifier_body |
format.rs | use super::{
Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10,
EventFormatSerializerV03, EventFormatSerializerV10,
};
use crate::event::{AttributesReader, ExtensionValue};
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use ... | <E: serde::de::Error>(v: Value) -> Result<Value, E> {
let data = parse_data_base64(v)?;
serde_json::from_slice(&data).map_err(E::custom)
}
pub(crate) trait EventFormatDeserializer {
fn deserialize_attributes<E: serde::de::Error>(
map: &mut Map<String, Value>,
) -> Result<Attributes, E>;
fn... | parse_data_base64_json | identifier_name |
format.rs | use super::{
Attributes, Data, Event, EventFormatDeserializerV03, EventFormatDeserializerV10,
EventFormatSerializerV03, EventFormatSerializerV10,
};
use crate::event::{AttributesReader, ExtensionValue};
use serde::de::{Error, IntoDeserializer};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use ... | map: &mut Map<String, Value>,
) -> Result<Attributes, E>;
fn deserialize_data<E: serde::de::Error>(
content_type: &str,
map: &mut Map<String, Value>,
) -> Result<Option<Data>, E>;
fn deserialize_event<E: serde::de::Error>(mut map: Map<String, Value>) -> Result<Event, E> {
... | fn deserialize_attributes<E: serde::de::Error>( | random_line_split |
dots.stories.js | import React from "react";
import { storiesOf } from "@storybook/react";
import { withKnobs, boolean } from "@storybook/addon-knobs";
import centered from "@storybook/addon-centered/react";
import DarkModeKnobWrapper from "./DarkModeKnobWrapper";
import Heart from "../components/dots/Heart";
import Pride from "../com... | <DarkModeKnobWrapper>
<Pride on={boolean("On", false)} />
</DarkModeKnobWrapper>
))
.add("Triangle", () => <Triangle on={boolean("On", false)} />)
.add("Vroom", () => <Vroom on={boolean("On", false)} />)
.add("Pulse", () => <Pulse on={boolean("On", false)} />); | })
.add("Pride", () => ( | random_line_split |
PrimeSieve.py | import math
def isPrime(num):
if num < 2:
return False # 0, 1不是质数
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根
boundary = int(math.sqrt(num)) + 1
for i in range(2, boundary):
if num % i == 0:
return False
return True
def primeSieve(size):... | return ret
if __name__ == '__main__':
primes = primeSieve(100)
primesString = ", ".join(primes)
print("prime : ", primesString)
'''
prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
''' | for i in range(size):
if sieve[i] == True:
ret.append(str(i)) | random_line_split |
PrimeSieve.py | import math
def isPrime(num):
| ve[0] = False
sieve[1] = True
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根
boundary = int(math.sqrt(size)) + 1
for i in range(2, boundary):
pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数
while pointer < size:
sieve[pointer]... | if num < 2:
return False # 0, 1不是质数
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根
boundary = int(math.sqrt(num)) + 1
for i in range(2, boundary):
if num % i == 0:
return False
return True
def primeSieve(size):
sieve = [True] * size # 某格一为乘积,... | identifier_body |
PrimeSieve.py | import math
def isPrime(num):
if num < 2:
| num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根
boundary = int(math.sqrt(num)) + 1
for i in range(2, boundary):
if num % i == 0:
return False
return True
def primeSieve(size):
sieve = [True] * size # 某格一为乘积, 就置为False
sieve[0] = False
sieve[1] = True
... | return False # 0, 1不是质数
# | conditional_block |
PrimeSieve.py | import math
def | (num):
if num < 2:
return False # 0, 1不是质数
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根
boundary = int(math.sqrt(num)) + 1
for i in range(2, boundary):
if num % i == 0:
return False
return True
def primeSieve(size):
sieve = [True] * siz... | isPrime | identifier_name |
seriesPicker.js | /**
* Piwik - free/libre analytics platform
*
* Series Picker control addition for DataTable visualizations.
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, require) {
/**
* This class creates and manages the Series Picker for certain Dat... | (columnOrRowConfig) {
return columnOrRowConfig.displayed;
}
},
/**
* Returns the translation of a metric that can be selected.
*
* @param {String} metric The name of the metric, ie, 'nb_visits' or 'nb_actions'.
* @return {String} The metri... | isItemDisplayed | identifier_name |
seriesPicker.js | /**
* Piwik - free/libre analytics platform
*
* Series Picker control addition for DataTable visualizations.
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, require) {
/**
* This class creates and manages the Series Picker for certain Dat... | * $(picker).bind('placeSeriesPicker', function () {
* $(this.domElem).doSomething(...);
* });
*
* @param {dataTable} dataTable The dataTable instance to add a series picker to.
* @constructor
* @deprecated use the piwik-series-picker directive instead
*/
var SeriesPicker =... | *
* Events are triggered via jQuery, so you bind callbacks to them like this:
*
* var picker = new SeriesPicker(dataTable); | random_line_split |
seriesPicker.js | /**
* Piwik - free/libre analytics platform
*
* Series Picker control addition for DataTable visualizations.
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, require) {
/**
* This class creates and manages the Series Picker for certain Dat... |
}
return metric;
}
};
var exports = require('piwik/DataTableVisualizations/Widgets');
exports.SeriesPicker = SeriesPicker;
})(jQuery, require);
| {
return this.selectableColumns[i].translation;
} | conditional_block |
seriesPicker.js | /**
* Piwik - free/libre analytics platform
*
* Series Picker control addition for DataTable visualizations.
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
(function ($, require) {
/**
* This class creates and manages the Series Picker for certain Dat... |
},
/**
* Returns the translation of a metric that can be selected.
*
* @param {String} metric The name of the metric, ie, 'nb_visits' or 'nb_actions'.
* @return {String} The metric translation. If one cannot be found, the metric itself
* is... | {
return columnOrRowConfig.displayed;
} | identifier_body |
component.js | import Ember from 'ember';
const STATUS_HELP = {
pending: function(registration) {
return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!';
},
accepted: function(registration) {
if (registration.directSource) {
return registration.sourceN... | ,
actions: {
enablePopover() {
Ember.$('[data-toggle="popover"]').popover();
}
}
});
| {
if (registration.status === 'pending') {
return 'bg-warning';
} else if (registration.directSource && registration.status === 'accepted') {
return 'bg-success';
} else if (registration.status === 'accepted') {
return 'bg-info';
} else if (registratio... | identifier_body |
component.js | import Ember from 'ember';
const STATUS_HELP = {
pending: function(registration) {
return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!';
},
accepted: function(registration) {
if (registration.directSource) {
return registration.sourceN... | () {
this._super(...arguments);
Ember.run.schedule('afterRender', this, function() {
this.send('enablePopover');
});
},
colorClass: Ember.computed('registration.data.status', 'registration.data.sourceName', function() {
return this.getStatusColor(this.get('registrati... | init | identifier_name |
component.js | import Ember from 'ember';
const STATUS_HELP = {
pending: function(registration) {
return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!';
},
accepted: function(registration) {
if (registration.directSource) {
return registration.sourceN... | }),
getStatusColor(registration) {
if (registration.status === 'pending') {
return 'bg-warning';
} else if (registration.directSource && registration.status === 'accepted') {
return 'bg-success';
} else if (registration.status === 'accepted') {
return... |
helpText: Ember.computed('registration.data.status', function() {
let registration = this.get('registration.data');
return STATUS_HELP[registration.status](registration); | random_line_split |
tesstrain.py | #!/usr/bin/env python3
# (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# 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
# Unl... | ():
log.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console_formatter = logging.Formatter(
"[%(asctime)s] %(levelname)s - %(message)s", datefmt="%H:%M:%S"
)
console.setFormatter(console_formatter)
log.addHandler(console)
def setup_loggin... | setup_logging_console | identifier_name |
tesstrain.py | #!/usr/bin/env python3
# (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# 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
# Unl... |
def setup_logging_console():
log.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console_formatter = logging.Formatter(
"[%(asctime)s] %(levelname)s - %(message)s", datefmt="%H:%M:%S"
)
console.setFormatter(console_formatter)
log.addHandler(... | log = logging.getLogger() | random_line_split |
tesstrain.py | #!/usr/bin/env python3
# (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# 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
# Unl... | return 0
if __name__ == "__main__":
main()
# _rc0 = subprocess.call(["tlog","\n=== Starting training for language '"+str(LANG_CODE.val)+"'"],shell=True)
# _rc0 = subprocess.call(["source",os.popen("dirname "+__file__).read().rstrip("\n")+"/language-specific.sh"],shell=True)
# _rc0 = subprocess.call(["set_la... | setup_logging_console()
ctx = parse_flags()
setup_logging_logfile(ctx.log_file)
if not ctx.linedata:
log.error("--linedata_only is required since only LSTM is supported")
sys.exit(1)
log.info(f"=== Starting training for language {ctx.lang_code}")
ctx = language_specific.set_lang_spe... | identifier_body |
tesstrain.py | #!/usr/bin/env python3
# (C) Copyright 2014, Google Inc.
# (C) Copyright 2018, James R Barlow
# 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
# Unl... |
sys.path.insert(0, os.path.dirname(__file__))
from tesstrain_utils import (
parse_flags,
initialize_fontconfig,
phase_I_generate_image,
phase_UP_generate_unicharset,
phase_E_extract_features,
make_lstmdata,
cleanup,
)
import language_specific
log = logging.getLogger()
def setup_logging_... | raise Exception("Must be using Python minimum version 3.6!") | conditional_block |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use Surface;
use Api;
use version::Version;
use gl;
pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>,
... |
}
if let Some(stencil) = stencil {
let stencil = stencil as gl::types::GLint;
flags |= gl::STENCIL_BUFFER_BIT;
if ctxt.state.clear_stencil != stencil {
ctxt.gl.ClearStencil(stencil);
ctxt.state.clear_stencil = stencil;
}... | {
ctxt.gl.DepthMask(gl::TRUE);
ctxt.state.depth_mask = true;
} | conditional_block |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use Surface;
use Api;
use version::Version;
use gl;
pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>,
... | if ctxt.version >= &Version(Api::Gl, 3, 0) {
ctxt.gl.EndConditionalRender();
} else if ctxt.extensions.gl_nv_conditional_render {
ctxt.gl.EndConditionalRenderNV();
} else {
unreachable!();
}
ctxt.state.condition... | {
unsafe {
let mut ctxt = context.make_current();
let fbo_id = context.get_framebuffer_objects()
.get_framebuffer_for_drawing(framebuffer, &mut ctxt);
fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false);
if ctxt.state.enabled_rasterizer_discard {
... | identifier_body |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use Surface;
use Api;
use version::Version;
use gl;
pub fn clear(context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>,
... | {
unsafe {
let mut ctxt = context.make_current();
let fbo_id = context.get_framebuffer_objects()
.get_framebuffer_for_drawing(framebuffer, &mut ctxt);
fbo::bind_framebuffer(&mut ctxt, fbo_id, true, false);
if ctxt.state.enabled_rasterizer_discard {
... | random_line_split | |
clear.rs | use fbo::{self, ValidatedAttachments};
use context::Context;
use ContextExt;
use Rect;
use Surface;
use Api;
use version::Version;
use gl;
pub fn | (context: &Context, framebuffer: Option<&ValidatedAttachments>,
rect: Option<&Rect>, color: Option<(f32, f32, f32, f32)>, depth: Option<f32>,
stencil: Option<i32>)
{
unsafe {
let mut ctxt = context.make_current();
let fbo_id = context.get_framebuffer_objects()
... | clear | identifier_name |
imp.rs | u32,
) {
unsafe {
let fls = (*stx).srcpad.pad_flags();
gst_trace!(CAT, "creamtxbw Handling buffer from scream len={}, seq_nr {}, ts {}, pt {}, is_mark {}, ssrc {} {:?}",
len, seq_nr, ts, pt, is_mark, ssrc, fls);
if fls.contains(gst::PadFlags::EOS) {
println!("... | random_line_split | ||
imp.rs | 8,
ssrc: u32,
),
);
fn ScreamTxBwPluginSetTargetRate(rate: u32);
fn ScreamTxBwPluginSetForceKeyUnit();
}
// This trait registers our type with the GObject object system and
// provides the entry points for creating a new instance and setting
// up the class data
#[glib::object_subclass]... | {
gst_info!(CAT, obj: element, "Changing state {:?}", transition);
// Call the parent class' implementation of ::change_state()
self.parent_change_state(element, transition)
} | identifier_body | |
imp.rs | of gst::Event and gst::EventRef to see what can be done with
// events, and especially the gst::EventView type for inspecting events.
fn sink_event(&self, pad: &gst::Pad, _element: &super::Screamtxbw, event: gst::Event) -> bool {
gst_log!(
CAT,
obj: pad,
"gstscream H... | else if fls.contains(gst::PadFlags::FLUSHING) {
println!("screamtxbw FL {:?}", fls);
return;
}
let mut buffer = gst::Buffer::new_rtp_with_sizes(len, 4, 0).unwrap();
{
let buffer = buffer.get_mut().unwrap();
let mut rtp_buffer = RTPBuffer::from_buf... | {
println!("screamtxbw EOS {:?}", fls);
return;
} | conditional_block |
imp.rs | {
params: Option<String>,
bitrate: u32,
}
impl Default for Settings {
fn default() -> Self {
Settings {
params: None,
bitrate: DEFAULT_BITRATE,
}
}
}
// static STREAMTX_PTR: Option<&Screamtxbw> = None;
// Struct containing all the element data
#[repr(C)]
pub ... | Settings | identifier_name | |
rustc.rs | use crate::command_prelude::*;
use cargo::ops;
pub fn | () -> App {
subcommand("rustc")
.setting(AppSettings::TrailingVarArg)
.about("Compile a package, and pass extra options to the compiler")
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg(Arg::with_name("args").multiple(true).help("Rustc flags"))
.arg_package(... | cli | identifier_name |
rustc.rs | use crate::command_prelude::*;
use cargo::ops;
pub fn cli() -> App {
subcommand("rustc")
.setting(AppSettings::TrailingVarArg)
.about("Compile a package, and pass extra options to the compiler")
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg(Arg::with_name("args"... | )
}
pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
let ws = args.workspace(config)?;
let mode = match args.value_of("profile") {
Some("dev") | None => CompileMode::Build,
Some("test") => CompileMode::Test,
Some("bench") => CompileMode::Bench,
Some... | `build.rustflags` configuration option.
", | random_line_split |
rustc.rs | use crate::command_prelude::*;
use cargo::ops;
pub fn cli() -> App | .arg_release("Build artifacts in release mode, with optimizations")
.arg_profile("Build artifacts with the specified profile")
.arg_features()
.arg_target_triple("Target triple which compiles will be for")
.arg_target_dir()
.arg_manifest_path()
.arg_message_format... | {
subcommand("rustc")
.setting(AppSettings::TrailingVarArg)
.about("Compile a package, and pass extra options to the compiler")
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg(Arg::with_name("args").multiple(true).help("Rustc flags"))
.arg_package("Package t... | identifier_body |
_serialize.py | # -*- coding: utf-8 -*-
# Copyright 2016 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Code for... |
def _py2_to_py3(items):
assert PY3
for i in items:
try:
l = list(i.items())
except AttributeError:
raise SerializationError
i.clear()
for k, v in l:
if isinstance(k, bytes):
k = k.decode("utf-8", "replace")
else:... | pass | identifier_body |
_serialize.py | # -*- coding: utf-8 -*-
# Copyright 2016 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Code for... | error_occured = []
temp_type_cache = {}
def lookup_func(base, module, name):
try:
real_type = base(module, name)
except (ImportError, AttributeError):
error_occured.append(True)
return dummy
if module.split(".")[0] not in ("quodlibet", "tests"):
... | SerializationError
"""
dummy = type("dummy", (dict,), {}) | random_line_split |
_serialize.py | # -*- coding: utf-8 -*-
# Copyright 2016 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Code for... | (items):
assert PY3
for i in items:
try:
l = list(i.items())
except AttributeError:
raise SerializationError
i.clear()
for k, v in l:
if isinstance(k, bytes):
k = k.decode("utf-8", "replace")
else:
#... | _py2_to_py3 | identifier_name |
_serialize.py | # -*- coding: utf-8 -*-
# Copyright 2016 Christoph Reiter
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
"""Code for... |
for item, key, value in fixups:
item[key] = value
return items
def load_audio_files(data, process=True):
"""unpickles the item list and if some class isn't found unpickle
as a dict and filter them out afterwards.
In case everything gets filtered out will raise SerializationError
(b... | fixups.append((i, k, text_type(v))) | conditional_block |
io_ops_filter.py | # Copyright (c) 2012 OpenStack, LLC.
# 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 requi... |
return passes
| LOG.debug(_("%(host_state)s fails I/O ops check: Max IOs per host "
"is set to %(max_io_ops)s"), locals()) | conditional_block |
io_ops_filter.py | # Copyright (c) 2012 OpenStack, LLC.
# 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 requi... | LOG = logging.getLogger(__name__)
max_io_ops_per_host_opt = cfg.IntOpt("max_io_ops_per_host",
default=8,
help="Ignore hosts that have too many builds/resizes/snaps/migrations")
CONF = cfg.CONF
CONF.register_opt(max_io_ops_per_host_opt)
class IoOpsFilter(filters.BaseHostFilter):
"""Filter out hos... | from nova.scheduler import filters
| random_line_split |
io_ops_filter.py | # Copyright (c) 2012 OpenStack, LLC.
# 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 requi... | """Filter out hosts with too many concurrent I/O operations."""
def host_passes(self, host_state, filter_properties):
"""Use information about current vm and task states collected from
compute node statistics to decide whether to filter.
"""
num_io_ops = host_state.num_io_ops
... | identifier_body | |
io_ops_filter.py | # Copyright (c) 2012 OpenStack, LLC.
# 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 requi... | (self, host_state, filter_properties):
"""Use information about current vm and task states collected from
compute node statistics to decide whether to filter.
"""
num_io_ops = host_state.num_io_ops
max_io_ops = CONF.max_io_ops_per_host
passes = num_io_ops < max_io_ops
... | host_passes | identifier_name |
ffi.rs | // Copyright 2014-2015 Sam Doshi (sam@metal-fish.co.uk)
// Copyright 2013-2014 Philippe Delrieu (philippe.delrieu@free.fr)
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
use libc::{c_char, c... | -9996 => Some(PmError::PmBufferOverflow),
-9995 => Some(PmError::PmBadPtr),
-9994 => Some(PmError::PmBadData),
-9993 => Some(PmError::PmInternalError),
-9992 => Some(PmError::PmBufferMaxSize),
_ => None
}
}
#[link(name = "portmidi")]
extern "C" {
pub fn Pm_Initia... | 1 => Some(PmError::PmGotData),
-10000 => Some(PmError::PmHostError),
-9999 => Some(PmError::PmInvalidDeviceId),
-9998 => Some(PmError::PmInsufficientMemory),
-9997 => Some(PmError::PmBufferTooSmall), | random_line_split |
ffi.rs | // Copyright 2014-2015 Sam Doshi (sam@metal-fish.co.uk)
// Copyright 2013-2014 Philippe Delrieu (philippe.delrieu@free.fr)
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
use libc::{c_char, c... | {
pub message : PmMessage,
pub timestamp : PmTimestamp,
}
#[repr(C)]
pub struct PmDeviceInfo {
pub struct_version: i32, /* < this internal structure version */
pub interf : *const c_char, /* < underlying MIDI API, e.g. MMSystem or DirectX */
pub name : *const c_char, /* < device name, e.g. USB ... | PmEvent | identifier_name |
02ccb3e6a553_.py | """empty message
Revision ID: 02ccb3e6a553
Revises: None
Create Date: 2016-05-17 22:15:03.881575
"""
# revision identifiers, used by Alembic.
revision = '02ccb3e6a553'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... | op.drop_index(op.f('ix_roles_default'), table_name='roles')
op.drop_table('roles')
### end Alembic commands ### | op.drop_table('users') | random_line_split |
02ccb3e6a553_.py | """empty message
Revision ID: 02ccb3e6a553
Revises: None
Create Date: 2016-05-17 22:15:03.881575
"""
# revision identifiers, used by Alembic.
revision = '02ccb3e6a553'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###... | sa.Column('last_seen', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
... | op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('default', sa.Boolean(), nullable=True),
sa.Column('permissions', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
... | identifier_body |
02ccb3e6a553_.py | """empty message
Revision ID: 02ccb3e6a553
Revises: None
Create Date: 2016-05-17 22:15:03.881575
"""
# revision identifiers, used by Alembic.
revision = '02ccb3e6a553'
down_revision = None
from alembic import op
import sqlalchemy as sa
def | ():
### commands auto generated by Alembic - please adjust! ###
op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('default', sa.Boolean(), nullable=True),
sa.Column('permissions', sa.Integer(), nullable=True)... | upgrade | identifier_name |
stations.js | 'use strict';
/* jshint indent:false */
/* global angular */
angular.module('emfd.views.stations', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/stations/:system/:station/:ref', {
templateUrl: 'js/views/stations/stations.html' | });
}])
.controller('StationController', [
'$scope', '$routeParams', 'dataStore', 'websocket', 'commander',
function($scope, $routeParams, dataStore, websocket, commander) {
$scope.system = $routeParams.system;
$scope.station = $routeParams.station;
$scope.ref = $routeParams.ref;
$... | , controller: 'StationController' | random_line_split |
register-mocks.ts | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | ,
},
});
}
/**
* The path to the mocked gcloud.
*/
export const gcloudPath = '/mocked/tools/gcloud';
/**
* The path to the mocked kubectl.
*/
export const kubectlPath = '/mocked/tools/kubectl';
/**
* The gcloud version execution string.
*/
export const gcloudVersionExecString = `${gcloudPath} version --f... | {
if (files && files.has(file)) {
return files.get(file);
} else {
return fs.readFileSync.apply(fs, arguments);
}
} | identifier_body |
register-mocks.ts | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | * @param files A map from filename to file contents. Files in the map will
* simply have the map content string output. Files not in the map will be read
* normally.
*/
export function getFsMock(files?: Map<string, string>): typeof fs {
return Object.create(fs, {
unlinkSync : {
value(file: string) : voi... |
/**
* Gets an object that mocks fs, replacing unlinkSync and readFileSync but
* keeping all other functions the same. | random_line_split |
register-mocks.ts | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
},
},
});
}
/**
* The path to the mocked gcloud.
*/
export const gcloudPath = '/mocked/tools/gcloud';
/**
* The path to the mocked kubectl.
*/
export const kubectlPath = '/mocked/tools/kubectl';
/**
* The gcloud version execution string.
*/
export const gcloudVersionExecString = `${gcloudPath}... | {
return fs.readFileSync.apply(fs, arguments);
} | conditional_block |
register-mocks.ts | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | (): TaskLibAnswers {
return {
which : {
'gcloud' : gcloudPath,
'kubectl' : kubectlPath,
},
checkPath : {
[gcloudPath] : true,
[kubectlPath] : true,
},
exec : {
[gcloudVersionExecString] : {
code : 0,
stdout : JSON.stringify({['Google Cloud SDK']: '174.... | getDefaultAnswers | identifier_name |
crc32_combine.py | '''
https://github.com/toomuchio/pycrc32combine
'''
def gf2_matrix_square(square, mat):
for n in range(0, 32):
if (len(square) < (n + 1)):
square.append(gf2_matrix_times(mat, mat[n]))
else: | def gf2_matrix_times(mat, vec):
sum = 0
i = 0
while vec:
if (vec & 1):
sum = sum ^ mat[i]
vec = (vec >> 1) & 0x7FFFFFFF
i = i + 1
return sum
def crc32_combine(crc1, crc2, len2):
even = []
odd = []
if (len2 == 0):
return crc1
odd.append(0xEDB88320L)
row = 1
for n in range(1, 32):
odd.append(row... | square[n] = gf2_matrix_times(mat, mat[n])
return square
| random_line_split |
crc32_combine.py | '''
https://github.com/toomuchio/pycrc32combine
'''
def gf2_matrix_square(square, mat):
for n in range(0, 32):
if (len(square) < (n + 1)):
square.append(gf2_matrix_times(mat, mat[n]))
else:
square[n] = gf2_matrix_times(mat, mat[n])
return square
def gf2_matrix_times(mat, vec):
sum = 0
i = 0
while vec:
... |
len2 = len2 >> 1
crc1 = crc1 ^ crc2
return crc1
| crc1 = gf2_matrix_times(odd, crc1) | conditional_block |
crc32_combine.py | '''
https://github.com/toomuchio/pycrc32combine
'''
def gf2_matrix_square(square, mat):
for n in range(0, 32):
if (len(square) < (n + 1)):
square.append(gf2_matrix_times(mat, mat[n]))
else:
square[n] = gf2_matrix_times(mat, mat[n])
return square
def | (mat, vec):
sum = 0
i = 0
while vec:
if (vec & 1):
sum = sum ^ mat[i]
vec = (vec >> 1) & 0x7FFFFFFF
i = i + 1
return sum
def crc32_combine(crc1, crc2, len2):
even = []
odd = []
if (len2 == 0):
return crc1
odd.append(0xEDB88320L)
row = 1
for n in range(1, 32):
odd.append(row)
row = row << 1
... | gf2_matrix_times | identifier_name |
crc32_combine.py | '''
https://github.com/toomuchio/pycrc32combine
'''
def gf2_matrix_square(square, mat):
|
def gf2_matrix_times(mat, vec):
sum = 0
i = 0
while vec:
if (vec & 1):
sum = sum ^ mat[i]
vec = (vec >> 1) & 0x7FFFFFFF
i = i + 1
return sum
def crc32_combine(crc1, crc2, len2):
even = []
odd = []
if (len2 == 0):
return crc1
odd.append(0xEDB88320L)
row = 1
for n in range(1, 32):
odd.append(r... | for n in range(0, 32):
if (len(square) < (n + 1)):
square.append(gf2_matrix_times(mat, mat[n]))
else:
square[n] = gf2_matrix_times(mat, mat[n])
return square | identifier_body |
LionSoftJs-0.1.1.ts | Returns the index of the first match of the regexp in the string. -1 if there is no match.
*/
RegexIndexOf(regex, startPos?: number): number;
/**
Returns the index of the last match of the regexp in the string. -1 if there is no match.
*/
RegexLastIndexOf(regex, startPos?: number): ... | reateGUID();
}
module LionSoftJs {
'use strict';
/**
Gets the folder of the LionSoft.Js-{version}.js script with trailing separator, eg. http[s]://server.name[:port][/appFolder]/Scripts/LionSoft.Js/
Warning! If minification bundles is used - you should set this parameter manually to correct val... | onSoftJs.C | identifier_name |
LionSoftJs-0.1.1.ts | the specified index and contains the specified number of elements.
*/
IndexOf(element: T, startIndex?: number, count?: number): number;
/**
Searches for the specified object and returns the zero-based index of the last occurrence within the range
of elements in the array that contains the... | eredObject();
script = updateScriptPath(script);
if (loadingJs.indexOf(script) !== -1 || loadedJs.indexOf(script) !== -1) {
res.invoke();
return res;
}
loadingJs.push(script);
var scriptElement = document.createElement("script");
scriptElement.typ... | identifier_body | |
LionSoftJs-0.1.1.ts | }
/**
Sets cookie value and its options.
--
Using:
> LionSoftJs.setCookie("myCookie", value, {expires: 10, path: "/", }) - set site cookie for 10 seconds
*/
export function setCookie(name: string, value: any, options?: any) {
options = options || {};
option... |
// Set window.location.appFolder | random_line_split | |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::cell::DOMRefCell;
... | (());
impl Console {
fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) {
if let Some(chan) = global.devtools_chan() {
let console_message = prepare_message(level, message);
let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI(
globa... | Console | identifier_name |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::cell::DOMRefCell;
... |
}
}
impl Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
pub fn Log(global: GlobalRef, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
Self::send_to_devtools(global, LogLevel::Log, message);
}
}
// ht... | {
let console_message = prepare_message(level, message);
let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI(
global.pipeline_id(),
console_message,
global.get_worker_id());
chan.send(devtools_message).unwrap();
} | conditional_block |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::cell::DOMRefCell;
... | }
impl Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
pub fn Log(global: GlobalRef, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
Self::send_to_devtools(global, LogLevel::Log, message);
}
}
// https://d... | console_message,
global.get_worker_id());
chan.send(devtools_message).unwrap();
}
} | random_line_split |
console.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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::cell::DOMRefCell;
... |
}
| {
self.0.borrow_mut().remove(label).ok_or(()).map(|start| {
timestamp_in_ms(get_time()) - start
})
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.