file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
device_tracker.py
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OP...
(DeviceScanner): """This class queries a router running OPNsense.""" def __init__(self, client, interfaces): """Initialize the scanner.""" self.last_results = {} self.client = client self.interfaces = interfaces def _get_mac_addrs(self, devices): """Create dict with...
OPNSenseDeviceScanner
identifier_name
device_tracker.py
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OP...
def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self.update_info() return list(self.last_results) def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if device not in self.las...
return out_devices
random_line_split
devops_borat.py
from random import choice from feedparser import parse from errbot import botcmd, BotPlugin class DevOpsBorat(BotPlugin): """ Quotes from various dev humour related twitter accounts """ @botcmd def borat(self, mess, args): """ Random quotes from the DEVOPS_BORAT twitter account ...
""" Random quotes from the UXYoda twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=UXYoda') items = myfeed['entries'] return choice(items).description
return choice(items).description @botcmd def yoda(self, mess, args):
random_line_split
devops_borat.py
from random import choice from feedparser import parse from errbot import botcmd, BotPlugin class DevOpsBorat(BotPlugin): """ Quotes from various dev humour related twitter accounts """ @botcmd def borat(self, mess, args): """ Random quotes from the DEVOPS_BORAT twitter account ...
(self, mess, args): """ Random quotes from the UXYoda twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=UXYoda') items = myfeed['entries'] return choice(items).description
yoda
identifier_name
devops_borat.py
from random import choice from feedparser import parse from errbot import botcmd, BotPlugin class DevOpsBorat(BotPlugin): """ Quotes from various dev humour related twitter accounts """ @botcmd def borat(self, mess, args):
@botcmd def jesus(self, mess, args): """ Random quotes from the devops_jesus twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=devops_jesus') items = myfeed['entries'] return choice(items).description @botcm...
""" Random quotes from the DEVOPS_BORAT twitter account """ myfeed = parse('http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=DEVOPS_BORAT') items = myfeed['entries'] return choice(items).description
identifier_body
test_plugins.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
def test_plugin__init_config_str(self): self.assertPluginLoaderConfigBecomes('test', ['test']) def test_plugin__init_config_none(self): self.assertPluginLoaderConfigBecomes(None, [])
config = ['/one', '/two'] self.assertPluginLoaderConfigBecomes(config, config)
identifier_body
test_plugins.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
pl = PluginLoader('test', '', 'test', 'test_plugin') pl._paths = ['/path/one', '/path/two'] self.assertEqual(pl._get_paths(), ['/path/one', '/path/two']) # NOT YET WORKING # def fake_glob(path): # if path == 'test/*': # return ['test/foo', 'test/bar',...
def test_plugins__get_paths(self):
random_line_split
test_plugins.py
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
(self): self.assertPluginLoaderConfigBecomes(None, [])
test_plugin__init_config_none
identifier_name
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str)
/** * Signs in a user using user obejct * * @param {Object} user - user object * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance */ function signinWithUser(user, req, res, onSuccess) { if (argum...
{ // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); }
identifier_body
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function
(str) { // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); } /** * Signs in a user using user obejct * * @param...
hash
identifier_name
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str) { // force type str = '' + str; // get the first half str...
doSignin(lookup, req, res, onSuccess, onFail); }); }; /** * Signs the current user out and resets the session * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.signout = function(req, res, next) { keystone.callHoo...
{ return onFail(err); }
conditional_block
session.js
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str) { // force type str = '' + str; // get the first half str...
onSuccess(user); }); } exports.signinWithUser = signinWithUser; var postHookedSigninWithUser = function(user, req, res, onSuccess, onFail) { keystone.callHook(user, 'post:signin', function(err) { if (err) { return onFail(err); } exports.signinWithUser(user, req, res, onSuccess, onFail); }); }; /** * S...
var userToken = user.id + ':' + hash(user.password); res.cookie('keystone.uid', userToken, { signed: true, httpOnly: true }); }
random_line_split
widget-picker-filter-view.js
define(function(require) { 'use strict'; var WidgetPickerFilterView; var _ = require('underscore'); var BaseView = require('oroui/js/app/views/base/view'); WidgetPickerFilterView = BaseView.extend({ template: require('tpl!oroui/templates/widget-picker/widget-picker-filter-view.html'), ...
*/ onSearch: function(e) { this.model.set('search', e.currentTarget.value); } }); return WidgetPickerFilterView; });
/** * * @param {Event} e
random_line_split
app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new Orth...
deck.setProps({layers}); } /* global document */ document.body.style.margin = '0px';
random_line_split
app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new Orth...
/* global document */ document.body.style.margin = '0px';
{ const buffer = new Buffer(gl, data); const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16}; const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16}; const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]); const layers = [ new SolidPolygonLayer({ ...
identifier_body
app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new Orth...
(gl) { const buffer = new Buffer(gl, data); const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16}; const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16}; const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]); const layers = [ new SolidPolygonLayer({ ...
onWebGLInitialized
identifier_name
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
ctx: CanvasRenderingContext2d, etsystem: Box<dyn EscapeTime>, ) -> EscapeTimeAnimation { let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTi...
impl EscapeTimeAnimation { pub fn new(
random_line_split
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
}) .flatten() .collect::<Vec<&u8>>() }) .flatten() .cloned() .collect::<Vec<u8>>(); // Construct a Clamped Uint8 Array log::debug!("build clamped image array"); let clamped_image_array =...
{ colors[cmp::min(time, 50 - 1) as usize].0.iter() }
conditional_block
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
fn render(&self) { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); let vat = geometry::ViewAreaTransformer::new( [screen_width.into(), screen_height.into()], self.view_area[0], self.view_are...
{ let view_area_c = etsystem.default_view_area(); let view_area = [ geometry::Point::from(view_area_c[0]), geometry::Point::from(view_area_c[1]), ]; EscapeTimeAnimation { ctx, etsystem, view_area, } }
identifier_body
escapetime.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicab...
(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) -> bool { let screen_width = self.ctx.canvas().unwrap().width(); let screen_height = self.ctx.canvas().unwrap().height(); // get the vat for the current view area let vat = geometry::ViewAreaTransformer::new( [screen_width.into...
zoom
identifier_name
columnUtils.d.ts
// Type definitions for ag-grid v15.0.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { ColumnGroupChild } from "../entities/columnGroupChild"; import { OriginalColumnGroupChild } from "../entities/originalColumnGroupChild"; import { OriginalColumnGroup } from ...
{ private gridOptionsWrapper; calculateColInitialWidth(colDef: any): number; getOriginalPathForColumn(column: Column, originalBalancedTree: OriginalColumnGroupChild[]): OriginalColumnGroup[]; depthFirstOriginalTreeSearch(tree: OriginalColumnGroupChild[], callback: (treeNode: OriginalColumnGroupChild) =...
ColumnUtils
identifier_name
columnUtils.d.ts
// Type definitions for ag-grid v15.0.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { ColumnGroupChild } from "../entities/columnGroupChild"; import { OriginalColumnGroupChild } from "../entities/originalColumnGroupChild"; import { OriginalColumnGroup } from ...
depthFirstAllColumnTreeSearch(tree: ColumnGroupChild[], callback: (treeNode: ColumnGroupChild) => void): void; depthFirstDisplayedColumnTreeSearch(tree: ColumnGroupChild[], callback: (treeNode: ColumnGroupChild) => void): void; }
random_line_split
guildMemberAdd.js
const Log = require("../util/log.js"); const common = require("../util/common.js"); const setting_global = require("../settings.json"); const setting_color = setting_global.commands.user.guilds.color; const setting_mute = setting_global.commands.admin.mute; const setting = setting_global.events.memberAdd; module.expor...
.find("name", role))); if (setting.autoRole.random_color) member.addRole(member.guild.roles .find("name", setting_color.colors[common.getRandom(0, setting_color.colors.length)].role)); if (client.muted && setting.auto_mute) { let time = client.muted[member.id]; ...
if (setting.autoRole.role) setting.autoRole.role.forEach((role) => member.addRole(member.guild.roles
random_line_split
subjects.server.routes.ts
'use strict'; /** * Module dependencies */ var subjectsPolicy = require('../policies/subjects.server.policy'), subjects = require('../controllers/subjects.server.controller'); module.exports = function(app) { // Subjects collection routes app.route('/api/subjects').all(subjectsPolicy.isAllowed) ...
// subjects year collection routes app.route('/api/year/:year/semester/:semester').all(subjectsPolicy.isAllowed) .get(subjects.listyearsemester); // subjects year collection routes app.route('/api/year/:year/semester/').all(subjectsPolicy.isAllowed) .get(subjects.listyear); // subjec...
random_line_split
data-source-definition-spec.js
describe("DataSourceDefinition", function() { var DATA_SOURCE_NAME = "Lista de Medicamentos"; var ITEM_ID_1 = "item_ID_1"; var ITEM_ID_2 = "item_ID_2"; var dataSourceDefinition; beforeEach(function() { angular.mock.module('otusjs.survey'); inject(function(_$injector_) { dataSourceDefinition =...
}); }); describe("getID method", function() { it("should return the DATA_SOURCE_NAME without blank spaces and lower case", function() { expect(dataSourceDefinition.getID()).toBe("listademedicamentos"); }); }); describe("performBind method", function() { beforeEach(function() { data...
expect(dataSourceDefinition.isBinded()).toBe(true);
random_line_split
link_entity.js
_tmpl.link_entity = function( entity, tagName, returnHTML, count ){ if( !entity ) return false if( tagName && typeof tagName == 'object' ) return _tmpl.link_entity( entity, tagName['tagName'] || null, tagName['returnHTML'] || null, tagName['count'] || null ) tagName = tagName || 'a' re...
+ '</' + tagName + '>', returnHTML ) }
+ ( typeof count == 'undefined' ? '' : ' <small>(' + count + ')</small>' ) + '</span>'
random_line_split
link_entity.js
_tmpl.link_entity = function( entity, tagName, returnHTML, count ){ if( !entity ) return false if( tagName && typeof tagName == 'object' ) return _tmpl.link_entity( entity, tagName['tagName'] || null, tagName['returnHTML'] || null, tagName['count'] || null ) tagName = tagName || 'a' re...
else{ var entityId = entity['id'] } return _tmpl.export( '<' + tagName + (tagName == 'a' ? ' href="?infos=entity&id='+entityId+'"' : '') + ' class="link_entity" data-entityid="' + entityId + '" data-infos="[[ENTITY::' + entityId + ']]">' + (entity.picture && entity.picture.avatar ? '<i style="b...
{ var entityId = parseInt(entity) entity = _g.data.entities[entityId] }
conditional_block
RidgeSample.py
#!/usr/bin/env python import arff import numpy as np import sys from sklearn import preprocessing from sklearn.linear_model import RidgeClassifier from sklearn.feature_selection import RFE from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import StratifiedK...
gridSearch = GridSearchCV(pipeline,param_grid=paramGrid,verbose=verboseLevel,n_jobs=n_jobs,cv=n_crossValidation) gridSearch.fit(inputs,output) estimator = gridSearch.best_estimator_ print "Results: " print "Selected features: {0}".format(estimator.named_steps['RFE'].n_features_to_select) print "Solver: {0}".format(esti...
pipeline = Pipeline([("scaler",scaler),("RFE",selector),("classifier",classifier)]) paramGrid = dict(RFE__n_features_to_select=n_featuresToSelect, classifier__solver=solvers) # Do grid search
random_line_split
RidgeSample.py
#!/usr/bin/env python import arff import numpy as np import sys from sklearn import preprocessing from sklearn.linear_model import RidgeClassifier from sklearn.feature_selection import RFE from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import StratifiedK...
print "Categorical indices: {0}".format(categoricals) # Apply OneHotEncoder oneHotEncoder = preprocessing.OneHotEncoder(categorical_features=categoricals, sparse=False) print "Number of features: {0}".format(len(dataset['data'][0])) print "Number of samples: {0}".format(len(dataset['data'])) binData = oneHotEncoder.f...
if isinstance(dataset['attributes'][feature][1], list): categoricals.append(feature)
conditional_block
howcast.py
from __future__ import unicode_literals import re from .common import InfoExtractor class HowcastIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)' _TEST = { 'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly', 'md5': '8b743df908...
video_description = self._html_search_regex(r'<meta content=(?:"([^"]+)"|\'([^\']+)\') name=\'description\'', webpage, 'description', fatal=False) return { 'id': video_id, 'url': video_url, 'title': self._og_search_title(webpage), 'description...
video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)', webpage, 'video URL')
random_line_split
howcast.py
from __future__ import unicode_literals import re from .common import InfoExtractor class HowcastIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)' _TEST = { 'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly', 'md5': '8b743df908...
(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) self.report_extraction(video_id) video_url = self._search_regex(r'\'?file\'?: "(http://mobile-media\.howcast\.com/[0-9]+\.mp4)', webpage, ...
_real_extract
identifier_name
howcast.py
from __future__ import unicode_literals import re from .common import InfoExtractor class HowcastIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?howcast\.com/videos/(?P<id>\d+)' _TEST = { 'url': 'http://www.howcast.com/videos/390161-How-to-Tie-a-Square-Knot-Properly', 'md5': '8b743df908c42f60cf6496586c7f12c3', 'info_dict': { 'id': '390161', 'ext': 'mp4', 'descripti...
identifier_body
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License versi...
log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values(): info['adminStatus'] = info['adminStatus'] == 'poweredOn' info['operStatus'] = info['operStat...
identifier_body
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License versi...
return [rm]
info['adminStatus'] = info['adminStatus'] == 'poweredOn' info['operStatus'] = info['operStatus'] == 'running' info['snmpindex'] = info['vmid'] del info['vmid'] om = self.objectMap(info) om.id = self.prepId(om.displayName) rm.append(om)
conditional_block
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License versi...
import ObjectMap class Esx(SnmpPlugin): # compname = "os" relname = "guestDevices" modname = 'ZenPacks.zenoss.ZenossVirtualHostMonitor.VirtualMachine' columns = { '.1': 'snmpindex', '.2': 'displayName', '.4': 'osType', '.5': 'memory', '.6': 'admin...
import Globals from Products.DataCollector.plugins.CollectorPlugin \ import SnmpPlugin, GetTableMap from Products.DataCollector.plugins.DataMaps \
random_line_split
Esx.py
########################################################################### # # This program is part of Zenoss Core, an open source monitoring platform. # Copyright (C) 2009, Zenoss Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License versi...
(self, device, results, log): log.info('processing %s for device %s', self.name(), device.id) getdata, tabledata = results table = tabledata.get("vminfo") rm = self.relMap() for info in table.values(): info['adminStatus'] = info['adminStatus'] == 'poweredOn' ...
process
identifier_name
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host =...
(func): from nose.plugins.skip import SkipTest def wrapper(*args, **kwargs): raise SkipTest("Test %s is skipped" % func.__name__) wrapper.__name__ = func.__name__ return wrapper
skipped
identifier_name
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host =...
def interact(self, cmd, expect='beanstalkctl> '): self.beanstalkctl.sendline(cmd) self.beanstalkctl.expect_exact(expect) return self.get_response() def get_response(self): result = self.beanstalkctl.before if result.endswith('\x1b[K'): return result[:-6] ...
print "done."
random_line_split
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host =...
def base_setup(self): self._start_beanstalkd() beanstalkctl = ' '.join([ os.path.join( os.path.dirname(self.call('pwd')), 'bin', 'beanstalkctl'), '--host={0}'.format(self.beanstalkd_host), '--port={0}'.format(self...
print "Using beanstalkd: {0}".format(self.beanstalkd_path) print "Starting up the beanstalkd instance...", self.beanstalkd_instance = subprocess.Popen( [self.beanstalkd_path, '-p', str(self.beanstalkd_port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ...
identifier_body
base_spec.py
import os import signal import subprocess import beanstalkc import time import pexpect try: import unittest2 as unittest except ImportError: import unittest from beanstalkctl.util import BeanstalkdMixin class BaseSpec(unittest.TestCase, BeanstalkdMixin): beanstalkd_instance = None beanstalkd_host =...
return text.strip() def skipped(func): from nose.plugins.skip import SkipTest def wrapper(*args, **kwargs): raise SkipTest("Test %s is skipped" % func.__name__) wrapper.__name__ = func.__name__ return wrapper
text = text.replace(chunk, '')
conditional_block
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.uti...
def str_to_date(string, args=None): """Takes a string and converts it to a datetime object""" date = parse(string) if date: return date return '' @register.filter_function def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'): """ The format of datetime in exif is as follows: %Y:%m:%d %H...
return queryset.order_by(*args) @register.filter_function
random_line_split
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.uti...
@register.filter def split(str, splitter): return str.split(splitter) @register.filter def tag_split(str): str = "".join(str) str = str.replace(", ", ",") return str.split(",") @register.filter def make_range(value): try: value = int(value) if value > 0: return range(...
from datetime import timedelta range_type = 'add' # parse the range if '+' in range_: range_ = range_[1:len(range_)] if '-' in range_: range_type = 'subtract' range_ = range_[1:len(range_)] k, v = range_.split('=') set_range = { str(k): int(v) } # set th...
identifier_body
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.uti...
(path): from os.path import basename return basename(path) @register.filter def date_diff(value, date_to_compare=None): """Compare two dates and return the difference in days""" import datetime if not isinstance(value, datetime.datetime): return 0 if not isinstance(date_to_compare, dat...
basename
identifier_name
base_filters.py
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.uti...
return string[:int(arg)] else: return string return string @register.filter def rss_date(value, arg=None): """Formats a date according to the given format.""" from django.utils import formats from django.utils.dateformat import format from datetime import datetime if not v...
return string
conditional_block
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile from Products.Five.browser.pagetemplatefile import ViewPageTemplat...
host = getToolByName(self, 'MailHost') registry = getUtility(IRegistry) mail_settings = registry.forInterface(IMailSchema, prefix='plone') m_from = mail_settings.email_from_address try: host.send(mail_text, m_to, m_from, subject=subject, char...
mail_text = mail_text.encode(encoding)
conditional_block
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile from Products.Five.browser.pagetemplatefile import ViewPageTemplat...
(z3c.form.form.Form): """ Display event with form """ template = Zope3PageTemplateFile("templates/form.pt") fields = z3c.form.field.Fields(IBasicForm) ignoreContext = True enable_unload_protection = False output = None ### ! fieldeset fields['gender'].widgetFactory = z3c.form.br...
MyForm
identifier_name
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile as FiveViewPageTemplateFile from Products.CMFCore.utils import getToolByName from Products.CMFCore.interfaces import ISiteRoot from Products.CMFPlone.utils import _createObjectByType from Products.CMFPlone.interfaces.controlpanel import IMailSche...
from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile
random_line_split
myform.py
import random import zope.schema import zope.interface from zope.i18nmessageid import MessageFactory from zope.component import getUtility, getMultiAdapter from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile as Zope3PageTemplateFile from Products.Five.browser.pagetemplatefile import ViewPageTemplat...
form_frame = plone.z3cform.layout.wrap_form(MyForm, index=FiveViewPageTemplateFile("templates/layout.pt"))
data, errors = self.extractData() if errors: self.status = _(u"Please correct errors") return folder = self.context id = str(random.randint(0, 99999999)) new_obj = _createObjectByType("vfu.events.registration", folder, id, lastname = data['lastname'], ...
identifier_body
PrintConfig.js
define(["dojo/_base/declare", "dojo/Deferred", "dojo/promise/all", "dojo/_base/lang", "dojo/_base/array", "esri/arcgis/utils", "esri/lang", "esri/tasks/PrintTemplate", "esri/request" ], function( declare, Deferred, all, lang, array, arcgisUtils, esriLang, PrintTemplate, esriRequest) { return declare(null, { ...
return deferred.promise; } }); });
{ //var letterAnsiAPlate = new PrintTemplate(); // letterAnsiAPlate.layout = "Letter ANSI A Landscape"; var landscapeFormat = new PrintTemplate(); landscapeFormat.layout = "Letter ANSI A Landscape"; landscapeFormat.layoutOptions = this.printConfig.layoutOptions; landscape...
conditional_block
PrintConfig.js
define(["dojo/_base/declare", "dojo/Deferred", "dojo/promise/all", "dojo/_base/lang", "dojo/_base/array", "esri/arcgis/utils", "esri/lang", "esri/tasks/PrintTemplate", "esri/request" ], function( declare, Deferred, all, lang, array, arcgisUtils, esriLang, PrintTemplate, esriRequest) { return declare(null, { ...
deferred.resolve(true); return deferred.promise; }, _buildPrintLayouts: function() { var deferred = new Deferred(); if (this.printConfig.templates) { this.templates = this.printConfig.templates; array.forEach(this.templates, lang.hitch(this, function( template) ...
}; });
random_line_split
lib.rs
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT // file at the top-level directory of this distribution. //! A library for working with [Google Breakpad][breakpad]'s //! text-format [symbol files][symbolfiles]. //! //! The highest-level API provided by this crate is to use the //! [`Symbolizer`][symbolizer] struct...
} impl fmt::Display for SymbolResult { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SymbolResult::Ok(_) => write!(f, "Ok"), SymbolResult::NotFound => write!(f, "Not found"), SymbolResult::LoadError(ref e) => write!(f, "Load error: {}", e), ...
{ match (self, other) { (&SymbolResult::Ok(ref a), &SymbolResult::Ok(ref b)) => a == b, (&SymbolResult::NotFound, &SymbolResult::NotFound) => true, (&SymbolResult::LoadError(_), &SymbolResult::LoadError(_)) => true, _ => false, } }
identifier_body
lib.rs
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT // file at the top-level directory of this distribution. //! A library for working with [Google Breakpad][breakpad]'s //! text-format [symbol files][symbolfiles]. //! //! The highest-level API provided by this crate is to use the //! [`Symbolizer`][symbolizer] struct...
/// /// [simplemodule]: struct.SimpleModule.html /// [simpleframe]: struct.SimpleFrame.html pub fn fill_symbol(&self, module: &dyn Module, frame: &mut dyn FrameSymbolizer) { let k = key(module); self.ensure_module(module, &k); if let Some(SymbolResult::Ok(ref sym)) = self.symbols...
/// assert_eq!(f.source_file.unwrap(), r"c:\program files\microsoft visual studio 8\vc\include\swprintf.inl"); /// assert_eq!(f.source_line.unwrap(), 51); /// ```
random_line_split
lib.rs
// Copyright 2015 Ted Mielczarek. See the COPYRIGHT // file at the top-level directory of this distribution. //! A library for working with [Google Breakpad][breakpad]'s //! text-format [symbol files][symbolfiles]. //! //! The highest-level API provided by this crate is to use the //! [`Symbolizer`][symbolizer] struct...
(&self) -> Cow<str> { self.code_file .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn code_identifier(&self) -> Cow<str> { self.code_identifier .as_ref() .map_or(Cow::from(""), |s| Cow::Borrowed(&s[..])) } fn debug_file(&sel...
code_file
identifier_name
issue-182.ts
import {Connection} from "../../../src/connection/Connection"; import {Post} from "./entity/Post"; import {expect} from "chai"; import {PostStatus} from "./model/PostStatus"; describe("github issues > #182 enums are not saved properly", () => { let connections: Connection[]; before(async () => connections = a...
import "reflect-metadata"; import {createTestingConnections, closeTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
random_line_split
context.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/. */ //! The context within which style is calculated. #![deny(missing_docs)] use animation::{Animation, PropertyAnima...
(shared: &SharedStyleContext) -> Self { ThreadLocalStyleContext { style_sharing_candidate_cache: StyleSharingCandidateCache::new(), bloom_filter: StyleBloom::new(), new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(), ...
new
identifier_name
context.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/. */ //! The context within which style is calculated. #![deny(missing_docs)] use animation::{Animation, PropertyAnima...
/// recalculation can be sent. pub new_animations_sender: Sender<Animation>, /// A set of tasks to be run (on the parent thread) in sequential mode after /// the rest of the styling is complete. This is useful for infrequently-needed /// non-threadsafe operations. pub tasks: Vec<SequentialTask<E...
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>, /// The bloom filter used to fast-reject selector-matching. pub bloom_filter: StyleBloom<E>, /// A channel on which new animations that have been triggered by style
random_line_split
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the ...
if (this._dirtyInline) { this._processor.refreshInline(); this._dirtyInline = false; } } /** * Calls the quill history redo function */ public redo() { if (this._quill.history) { this._quill.history.redo(); } } /** * Rescans the entire document for highlighting. This is a wrapper around...
{ this._dirtyIdle = false; this._dirtyCount = 0; this._processor.refreshBlock(); }
conditional_block
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the ...
/** * Calls the processor's current header creation function * @param level {string} the level selected by the user */ public setHeader(level: string) { this._processor.handleHeader(Number(level)); } public setHighlight(name: string) { debug("setting highlight: %s", name); if (name in cssHighlights)...
{ debug("setting font size: %spx", fontSize); this._opts.fontSize = fontSize; this._editor.style["font-size"] = `${fontSize}px`; }
identifier_body
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the ...
const oldlink = document.getElementById("highlights"); const newlink = document.createElement("link"); newlink.setAttribute("id", "highlights"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", cssHighlights[name]); const head = doc...
public setHighlight(name: string) { debug("setting highlight: %s", name); if (name in cssHighlights) {
random_line_split
markup.ts
/** * A custom Quill highlighting module for markup modes/styles. It manages * multiple mode instances that are used to apply text formatting to the * contents of the control. * * The module is added to the component per the API instructions: * https://quilljs.com/guides/building-a-custom-module/ * * Once the ...
() { this._processor.refreshFull(); this._dirtyIdle = false; this._dirtyCount = 0; this._dirtyInline = false; } /** * Changes the current highlighting mode and display style. It also sets * the content within control. * @param opts {HighlightOptions} configuration options. `mode` sets the * editing...
refresh
identifier_name
module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {NglInternalOutletModule} from '../util/outlet.module'; import {NglFormElement} from './elements/element'; import {NglFormInput, NglFormTextarea, NglFormSelect, NglFormCheckbox} from './elements/input'; import {NglFormElementR...
{}
NglFormsModule
identifier_name
module.ts
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {NglInternalOutletModule} from '../util/outlet.module'; import {NglFormElement} from './elements/element'; import {NglFormInput, NglFormTextarea, NglFormSelect, NglFormCheckbox} from './elements/input'; import {NglFormElementR...
}) export class NglFormsModule {}
random_line_split
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError ...
""" score = 1100 @classmethod def to_python(cls, data): if not data.get('filename'): raise InterfaceValidationError("Missing 'filename'") if not data.get('context_line'): raise InterfaceValidationError("Missing 'context_line'") if not data.get('lineno'): ...
>>> ], >>> } .. note:: This interface can be passed as the 'template' key in addition to the full interface path.
random_line_split
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError ...
(Interface): """ A rendered template (generally used like a single frame in a stacktrace). The attributes ``filename``, ``context_line``, and ``lineno`` are required. >>> { >>> "abs_path": "/real/file/name.html" >>> "filename": "file/name.html", >>> "pre_context": [ >>> ...
Template
identifier_name
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError ...
def get_api_context(self, is_public=False): return { 'lineNo': self.lineno, 'filename': self.filename, 'context': get_context( lineno=self.lineno, context_line=self.context_line, pre_context=self.pre_context, ...
result = [ event.message, '', 'File "%s", line %s' % (self.filename, self.lineno), '', ] result.extend([n[1].strip('\n') for n in context]) return '\n'.join(result)
identifier_body
template.py
""" sentry.interfaces.template ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import __all__ = ('Template',) from sentry.interfaces.base import Interface, InterfaceValidationError ...
kwargs = { 'abs_path': trim(data.get('abs_path', None), 256), 'filename': trim(data['filename'], 256), 'context_line': trim(data.get('context_line', None), 256), 'lineno': int(data['lineno']), # TODO(dcramer): trim pre/post_context 'pre_c...
raise InterfaceValidationError("Missing 'lineno'")
conditional_block
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
isSudo() { return !!this.sudoId && this._sudoToken.isActive() } /** * retrieve the current authentication token. If there is no active token, performs default * login to retrieve the token */ async getToken() { if (!this.isAuthenticated()) { await this.login() } return this.act...
{ const token = await this.getToken() if (token && token.access_token) { props.headers.Authorization = `Bearer ${token.access_token}` } return props }
identifier_body
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
if (!this._authToken.isActive()) { this.reset() // only retain client API3 credentials for the lifetime of the login request const section = this.settings.readConfig() const clientId = section.client_id const clientSecret = section.client_secret if (!clientId || !clientSecret) ...
{ // Assign new requested sudo id this.sudoId = newId || '' }
conditional_block
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
() { return !!this.sudoId && this._sudoToken.isActive() } /** * retrieve the current authentication token. If there is no active token, performs default * login to retrieve the token */ async getToken() { if (!this.isAuthenticated()) { await this.login() } return this.activeToken ...
isSudo
identifier_name
nodeSession.ts
/* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
/** * Reset the authentication session */ reset() { this.sudoId = '' this._authToken.reset() this._sudoToken.reset() } /** * Activate the authentication token for the API3 or sudo user * @param sudoId {string | number}: optional. If provided, impersonates the user specified * */ ...
return this.activeToken }
random_line_split
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; t...
this._viewpos.set(viewx, 0.0, viewz); }; OrbitCamera.prototype.updateCam = function() { if(this._tracked) { this.updateTrack(); } this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate; this._phi += ( this._tarphi - this._phi ) * this._rate; this._cam.position.copy(sphericalToCartesian...
this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate; var viewx = Math.cos(this._tracktheta) * trackdist; var viewz = Math.sin(this._tracktheta) * trackdist;
random_line_split
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; t...
OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * this._radius; ...
{ var y = Math.sin(phi) * rad; var r2 = Math.cos(phi) * rad; var x = Math.cos(theta) * r2; var z = Math.sin(theta) * r2; var ret = new THREE.Vector3(x, y, z); if(offset) { ret.add(offset); } return ret; }
identifier_body
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; t...
return ret; } OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * t...
{ ret.add(offset); }
conditional_block
orbitcam.js
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; t...
() { mouseDownState = false; } function onWindowResize() { getSize(); camera.aspect = windowX / windowY; camera.updateProjectionMatrix(); renderer.setSize( windowX, windowY ); } function onCamDocumentKeyDown(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = true; } if(event.keyCode == panB...
onCamMouseUp
identifier_name
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blo...
(object): """ A pointer to a specific BundleVersion """ bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) version = attr.ib(type=int) snapshot_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class LinkDetails(object): """ Details about a specific link in a BundleVe...
LinkReference
identifier_name
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID):
return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blockstore collection """ uuid = attr.ib(type=UUID, converter=_convert_to_uuid) title = attr.ib(type=six.text_type) @attr.s(frozen=True) class Bundle(object): """ Metadata about a blockstore bundle ...
return UUID(value)
conditional_block
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blo...
url = attr.ib(type=six.text_type) hash_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class DraftFile(BundleFile): """ Metadata about a file in a blockstore draft. """ modified = attr.ib(type=bool) # Was this file modified in the draft? @attr.s(frozen=True) class LinkReference(ob...
""" path = attr.ib(type=six.text_type) size = attr.ib(type=int)
random_line_split
models.py
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blo...
""" Details about a specific link in a Draft """ modified = attr.ib(type=bool)
identifier_body
MuiColorChit.js
import React from 'react'; import { withTheme } from '@material-ui/core'; const MuiColorChit = (props) => { let { theme } = props; let chitStyle = { flexGrow: 0, flexShrink: 0, width: props.size === "small" ? '16px' : '24px', height: props.size === "small" ? '16px' : '24px', ...
height: props.isSelected ? '32px' : '24px', borderRadius: '50%', background: theme.palette.action.selected, transition: theme.transitions.create(['width', 'height', 'margin']), } containerStyle.width = props.size === "small" ? '16px' : containerStyle.width; containerStyle.he...
random_line_split
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _e...
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enum...
{ if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
identifier_body
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _e...
if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(...
{ continue; }
conditional_block
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _e...
(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "obje...
_classCallCheck
identifier_name
Link.js
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _e...
var deepEqual = function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? '...
var isModifiedEvent = function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); };
random_line_split
volume_cubic_inches_to_metric_test.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 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 import unitt...
"Total volume is 1-16 cb. in for this land. " "Total volume is 16.7-Cubic-in for this land. " "Total volume is 16,500-cu. in. for this land. " ) item = {"body_html": text} res, diff = cubic_inches_to_metric(item) self.assertEqual(diff["100.50 cubic inc...
"Total volume is 15.7 cubic in for this land. " "Total volume is 1 Cubic Inch for this land. " "Total volume is 1-16 cu-in for this land. "
random_line_split
volume_cubic_inches_to_metric_test.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 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 import unitt...
text = ( "Total volume is 100.50 cubic inches for this land. " "Total volume is 15.7 cubic in for this land. " "Total volume is 1 Cubic Inch for this land. " "Total volume is 1-16 cu-in for this land. " "Total volume is 1-16 cb. in for this land. " ...
identifier_body
volume_cubic_inches_to_metric_test.py
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 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 import unitt...
(unittest.TestCase): def test(self): text = ( "Total volume is 100.50 cubic inches for this land. " "Total volume is 15.7 cubic in for this land. " "Total volume is 1 Cubic Inch for this land. " "Total volume is 1-16 cu-in for this land. " "Total v...
VolumeTestCase
identifier_name
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, De...
(&self, _: &mut DVectorSliceMut<N>) {} fn integrate(&mut self, parameters: &IntegrationParameters<N>, vels: &[N]) { self.position += Vector::from_row_slice(&vels[..DIM]) * parameters.dt(); } fn apply_displacement(&mut self, disp: &[N]) { self.position += Vector::from_row_slice(&disp[..DIM]...
default_damping
identifier_name
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, De...
CartesianJoint { position } } } impl<N: RealField> Joint<N> for CartesianJoint<N> { #[inline] fn ndofs(&self) -> usize { DIM } fn body_to_parent(&self, parent_shift: &Vector<N>, body_shift: &Vector<N>) -> Isometry<N> { let t = Translation::from(parent_shift - body_shift + s...
impl<N: RealField> CartesianJoint<N> { /// Create a cartesian joint with an initial position given by `position`. pub fn new(position: Vector<N>) -> Self {
random_line_split
cartesian_joint.rs
use na::{self, DVectorSliceMut, RealField}; use crate::joint::Joint; use crate::math::{Isometry, JacobianSliceMut, Translation, Vector, Velocity, DIM}; use crate::solver::IntegrationParameters; /// A joint that allows only all the translational degrees of freedom between two multibody links. #[derive(Copy, Clone, De...
fn jacobian_dot_veldiff_mul_coordinates( &self, _: &Isometry<N>, _: &[N], _: &mut JacobianSliceMut<N>, ) { } fn jacobian_mul_coordinates(&self, vels: &[N]) -> Velocity<N> { Velocity::from_vectors(Vector::from_row_slice(&vels[..DIM]), na::zero()) } fn j...
{}
identifier_body
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can redistribute it and/or mo...
ser, scope): """ Generate a new signed token containing a specified user limited for a scope (identified as a string). """ data = {"user_%s_id" % (scope): user.id} return signing.dumps(data) def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope...
t_token_for_user(u
identifier_name
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can redistribute it and/or mo...
model_cls = apps.get_model("users", "User") try: user = model_cls.objects.get(pk=data["user_%s_id" % (scope)]) except (model_cls.DoesNotExist, KeyError): raise exc.NotAuthenticated(_("Invalid token")) else: return user
random_line_split
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can redistribute it and/or mo...
turn user
conditional_block
tokens.py
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can redistribute it and/or mo...
def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. ...
" Generate a new signed token containing a specified user limited for a scope (identified as a string). """ data = {"user_%s_id" % (scope): user.id} return signing.dumps(data)
identifier_body
pa-in.js
//! moment.js locale configuration //! locale : Punjabi (India) [pa-in] //! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof...
conditional_block
pa-in.js
//! moment.js locale configuration //! locale : Punjabi (India) [pa-in] //! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof...
return pa_in; }));
});
random_line_split
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
pub const HEAD_ADDRESS_OFFSET: usize = 4 + 4 + 8; pub const HEAD_KEY_LEN_OFFSET: usize = 4 + 4 + 8 + 20; pub const HEAD_TTL_OFFSET: usize = 4 + 4 + 8 + 20 + 1; pub const DEFAULT_TTL_NUM: u8 = 0; pub const CONSENSUS_TTL_NUM: u8 = 9; pub const CONSENSUS_STR: &str = "consensus"; #[derive(Debug, Clone)] pub struct NetMes...
pub const HEAD_VERSION_OFFSET: usize = 4 + 4;
random_line_split
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
} impl Default for NetMessageUnit { fn default() -> Self { NetMessageUnit { key: String::default(), data: Vec::new(), addr: Address::zero(), version: 0, ttl: DEFAULT_TTL_NUM, } } } pub fn pubsub_message_to_network_message(info: &NetM...
{ NetMessageUnit { key, data, addr, version, ttl, } }
identifier_body
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
(info: &NetMessageUnit) -> Option<Bytes> { let length_key = info.key.len(); // Use 1 byte to store key length. if length_key == 0 || length_key > u8::max_value() as usize { error!( "[CitaProtocol] The MQ message key is too long or empty {}.", info.key ); retur...
pubsub_message_to_network_message
identifier_name
cita_protocol.rs
// Copyright Cryptape Technologies LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed ...
Some(NetMessageUnit { key, data: buf.to_vec(), addr, version, ttl, }) } #[cfg(test)] mod test { use super::{ network_message_to_pubsub_message, pubsub_message_to_network_message, NetMessageUnit, }; use bytes::BytesMut; #[test] fn convert_emp...
{ warn!("[CitaProtocol] Network message is empty."); }
conditional_block
worker.js
// Generated by CoffeeScript 1.8.0 var BITSTR, DERNULL, INTERGER, OID, PRTSTR, SEQUENCE, SET, TAG, UTF8STR, asn1Util, cryptoUtil, generateCSR, generateKeyPair, j, keyUtil, onmessage; postMessage({ type: 'status', message: 'Importing JSRSASign library ...' }); importScripts('jsrsasign-4.7.0-all-min.js'); j = KJUR...
SET = function(arr) { return new j.asn1.DERSet({ 'array': arr }); }; INTERGER = function(num) { return new j.asn1.DERInteger({ 'int': num }); }; PRTSTR = function(str) { return new j.asn1.DERPrintableString({ 'str': str }); }; UTF8STR = function(str) { return new j.asn1.DERUTF8String({ ...
random_line_split