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
VirtualTimeScheduler.ts
import { AsyncAction } from './AsyncAction'; import { Subscription } from '../Subscription'; import { AsyncScheduler } from './AsyncScheduler'; export class VirtualTimeScheduler extends AsyncScheduler { protected static frameTimeFactor: number = 10; public frame: number = 0; public index: number = -1; const...
<T> extends AsyncAction<T> { constructor(protected scheduler: VirtualTimeScheduler, protected work: (this: VirtualAction<T>, state?: T) => void, protected index: number = scheduler.index += 1) { super(scheduler, work); this.index = scheduler.index = index; } public schedule(s...
VirtualAction
identifier_name
index.js
var DB = require('./lib/db.js'); function SQLContext(options) { this.readOnly = options.isReadOnly; this.db = options.db; } function _put(db, key, value, callback) { db.createOrUpdate(key, value, function(err) { if(err) { return callback(err); } callback(); }); } SQLContext.prototype.putObj...
SQLProvider.prototype.open = function(callback) { if(!this.user) { return callback(new Error('missing user')); } this.db = new DB(this.options, function(err) { if (err) { return callback(err); } callback(); }); }; SQLProvider.prototype.getReadOnlyContext = function() { return new SQLC...
SQLProvider.isSupported = function() { return (typeof module !== 'undefined' && module.exports); };
random_line_split
index.js
var DB = require('./lib/db.js'); function SQLContext(options) { this.readOnly = options.isReadOnly; this.db = options.db; } function _put(db, key, value, callback) { db.createOrUpdate(key, value, function(err) { if(err) { return callback(err); } callback(); }); } SQLContext.prototype.putObj...
SQLProvider.isSupported = function() { return (typeof module !== 'undefined' && module.exports); }; SQLProvider.prototype.open = function(callback) { if(!this.user) { return callback(new Error('missing user')); } this.db = new DB(this.options, function(err) { if (err) { return callback(err); ...
{ this.options = options || {}; this.user = options.user; }
identifier_body
index.js
var DB = require('./lib/db.js'); function SQLContext(options) { this.readOnly = options.isReadOnly; this.db = options.db; } function _put(db, key, value, callback) { db.createOrUpdate(key, value, function(err) { if(err) { return callback(err); } callback(); }); } SQLContext.prototype.putObj...
if(data) { try { data = JSON.parse(data.toString('utf8')); } catch(e) { return callback(e); } } callback(null, data); }); }; SQLContext.prototype.getBuffer = function(key, callback) { _get(this.db, key, callback); }; function SQLProvider(options) { this.options = ...
{ return callback(err); }
conditional_block
index.js
var DB = require('./lib/db.js'); function SQLContext(options) { this.readOnly = options.isReadOnly; this.db = options.db; } function _put(db, key, value, callback) { db.createOrUpdate(key, value, function(err) { if(err) { return callback(err); } callback(); }); } SQLContext.prototype.putObj...
(options) { this.options = options || {}; this.user = options.user; } SQLProvider.isSupported = function() { return (typeof module !== 'undefined' && module.exports); }; SQLProvider.prototype.open = function(callback) { if(!this.user) { return callback(new Error('missing user')); } this.db = new DB(t...
SQLProvider
identifier_name
color_space_10_8.py
""" HLS and Color Threshold ----------------------- You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore this a bit further and look at a couple examples to see why a color space like HLS can be more robust. """ import numpy as np import cv2 import matplot...
(): """ Run different HLS and its thresholds. """ image = mpimg.imread('test6.jpg') # Converting original to gray gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # Threshold for original image thresh = (180, 255) binary = np.zeros_like(gray) binary[(gray > thresh[0]) & (gray <= ...
run
identifier_name
color_space_10_8.py
""" HLS and Color Threshold ----------------------- You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore this a bit further and look at a couple examples to see why a color space like HLS can be more robust. """ import numpy as np import cv2 import matplot...
plt.title("Threshold of hue") plt.show() if __name__ == '__main__': run()
random_line_split
color_space_10_8.py
""" HLS and Color Threshold ----------------------- You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore this a bit further and look at a couple examples to see why a color space like HLS can be more robust. """ import numpy as np import cv2 import matplot...
if __name__ == '__main__': run()
""" Run different HLS and its thresholds. """ image = mpimg.imread('test6.jpg') # Converting original to gray gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # Threshold for original image thresh = (180, 255) binary = np.zeros_like(gray) binary[(gray > thresh[0]) & (gray <= thresh[1...
identifier_body
color_space_10_8.py
""" HLS and Color Threshold ----------------------- You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore this a bit further and look at a couple examples to see why a color space like HLS can be more robust. """ import numpy as np import cv2 import matplot...
run()
conditional_block
_npm.js
module.exports = { build_dll: function() { return new Promise(function (resolve, reject) { console.log("_postinstall > NPM: DLL build started. Please wait.."); require('child_process').execSync('npm run build:dll', {stdio:[0,1,2]}); console.log("_postinstall > NPM: DLL build completed"); ...
};
}); }); },
random_line_split
proxy.ts
import observable = require("data/observable"); import bindable = require("ui/core/bindable"); import dependencyObservable = require("ui/core/dependency-observable"); import types = require("utils/types"); import definition = require("ui/core/proxy"); export class PropertyMetadata extends dependencyObservable.Proper...
defaultValue: any, options?: number, onChanged?: dependencyObservable.PropertyChangedCallback, onValidateValue?: dependencyObservable.PropertyValidationCallback, onSetNativeValue?: dependencyObservable.PropertyChangedCallback) { super(defaultValue, opt...
nstructor(
identifier_name
proxy.ts
import observable = require("data/observable"); import bindable = require("ui/core/bindable"); import dependencyObservable = require("ui/core/dependency-observable"); import types = require("utils/types"); import definition = require("ui/core/proxy"); export class PropertyMetadata extends dependencyObservable.Proper...
get android(): any { return undefined; } /** * Gets the ios-specific native instance that lies behind this proxy. Will be available if running on an iOS platform. */ get ios(): any { return undefined; } public _onPropertyChanged(property: dependencyObservable.Propert...
*/
random_line_split
proxy.ts
import observable = require("data/observable"); import bindable = require("ui/core/bindable"); import dependencyObservable = require("ui/core/dependency-observable"); import types = require("utils/types"); import definition = require("ui/core/proxy"); export class PropertyMetadata extends dependencyObservable.Proper...
if (global.android && !this.android) { // in android we have lazy loading and we do not have a native widget created yet, do not call the onSetNativeValue callback // properties will be synced when the widget is created return; } var metadata = property.metad...
// This is the case when a property has changed from the native side directly and we have received the "_onPropertyChanged" event while synchronizing our local cache return; }
conditional_block
proxy.ts
import observable = require("data/observable"); import bindable = require("ui/core/bindable"); import dependencyObservable = require("ui/core/dependency-observable"); import types = require("utils/types"); import definition = require("ui/core/proxy"); export class PropertyMetadata extends dependencyObservable.Proper...
private _trySetNativeValue(property: dependencyObservable.Property, oldValue?:any, newValue?: any) { if (this._updatingJSPropertiesDict[property.name]) { // This is the case when a property has changed from the native side directly and we have received the "_onPropertyChanged" event while synchr...
var that = this; var eachPropertyCallback = function (property: dependencyObservable.Property): boolean { that._trySetNativeValue(property); return true; } this._eachSetProperty(eachPropertyCallback); }
identifier_body
playlist_rename_spec.py
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment with describe('ipodio playlist create') as _: @before.all def setup_all(): _.new_name = 'leño' _.playlist_name =...
ecution = _.env.run(*_.cmd + ['playlist', 'rename', _.playlist_name, _.new_name]) playlists = get_ipod_playlists_by_name(_.mountpoint_path) expect(playlists).to.have(_.new_name) expect(playlists).not_to.have(_.playlist_name) expect(execution.stdout).to.h...
identifier_body
playlist_rename_spec.py
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment with describe('ipodio playlist create') as _: @before.all def setup_all(): _.new_name = 'leño' _.playlist_name =...
with context('given an existing playlist name'): def should_print_an_error__(): execution = _.env.run(*_.cmd + ['playlist', 'rename'], expect_error=True) expect(execution.stderr).to.have('Usage:') with context('given an existing playlist name'): def should_print...
execution = _.env.run(*_.cmd + ['playlist', 'rename', _.new_name, _.playlist_name]) expect(execution.stdout).to.have('does not exist')
random_line_split
playlist_rename_spec.py
# -*- coding: utf-8 -*- from expects import expect from mamba import describe, context, before from spec.ui._ipod_helpers import * from spec.ui._fixture import update_environment with describe('ipodio playlist create') as _: @before.all def setup_all(): _.new_name = 'leño' _.playlist_name =...
: execution = _.env.run(*_.cmd + ['playlist', 'rename', _.playlist_name, _.new_name]) playlists = get_ipod_playlists_by_name(_.mountpoint_path) expect(playlists).to.have(_.new_name) expect(playlists).not_to.have(_.playlist_name) expect(ex...
ould_rename_that_playlist()
identifier_name
index.d.ts
// Type definitions for vanilla-tilt 1.4 // Project: https://github.com/micku7zu/vanilla-tilt.js // Definitions by: Livio Brunner <https://github.com/BrunnerLivio> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** * A smooth 3D tilt javascript library forked from Tilt.js (jQuery version). */ exp...
{ /** * Creates a new instance of a VanillaTilt element. * @param element The element, which should be a VanillaTilt element * @param settings Settings which configures the element */ constructor(element: HTMLElement, settings?: VanillaTilt.TiltOptions); /** * Initializes one or mu...
VanillaTilt
identifier_name
index.d.ts
// Type definitions for vanilla-tilt 1.4 // Project: https://github.com/micku7zu/vanilla-tilt.js // Definitions by: Livio Brunner <https://github.com/BrunnerLivio> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** * A smooth 3D tilt javascript library forked from Tilt.js (jQuery version). */ exp...
* Stop listening to events */ removeEventListener(): void; }
random_line_split
backtop.js
(function($, f) { // If there's no jQuery, Unslider can't work, so kill the operation. if(!$) return f; var Unslider = function() { // Set up our elements this.el = f; this.items = f; // Dimensions this.sizes = []; this.max = [0,0]; // Current inded this.current = 0; // Start/stop t...
}, scroll_top_duration ); }); //設定footer置底 var winheight = $( window ).height(); var bodyheight = $("body").height(); if (winheight >= bodyheight){ $(".outer-footer").css("position" , "fixed"); $(".outer-footer").css("bottom" , "0"); } }); ...
random_line_split
backtop.js
(function($, f) { // If there's no jQuery, Unslider can't work, so kill the operation. if(!$) return f; var Unslider = function() { // Set up our elements this.el = f; this.items = f; // Dimensions this.sizes = []; this.max = [0,0]; // Current inded this.current = 0; // Start/stop t...
tionality this.start = function() { _.interval = setInterval(function() { _.move(_.current + 1); }, _.opts.delay); }; // Stop autoplay this.stop = function() { _.interval = clearInterval(_.interval); return _; }; // Keypresses this.keys = function(e) { var key = e.which; var ...
sky dots _.el.find('.dot:eq(' + index + ')').addClass('active').siblings().removeClass('active'); this.el.animate(obj, speed) && this.ul.animate($.extend({left: '-' + index + '00%'}, obj), speed, function(data) { _.current = index; $.isFunction(_.opts.complete) && !cb && _.opts.complete(_.el); })...
conditional_block
virtual_machine_agent_instance_view.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.vm_agent_version = vm_agent_version self.extension_handlers = extension_handlers self.statuses = statuses
def __init__(self, vm_agent_version=None, extension_handlers=None, statuses=None):
random_line_split
virtual_machine_agent_instance_view.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """The instance view of the VM Agent running on the virtual machine. :param vm_agent_version: The VM Agent full version. :type vm_agent_version: str :param extension_handlers: The virtual machine extension handler instance view. :type extension_handlers: list of :class:`VirtualMa...
VirtualMachineAgentInstanceView
identifier_name
virtual_machine_agent_instance_view.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.vm_agent_version = vm_agent_version self.extension_handlers = extension_handlers self.statuses = statuses
identifier_body
imdb_rnn.py
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
max_features = 20000 maxlen = 100 # cut texts after this number of words batch_size = 32 print("Loading data...") (x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(num_words=max_features) print(len(x_train), "train sequences") print(len(x_test), "test sequences") print("Pad sequences ...
random_line_split
Districts.js
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/topic', 'dojo/on', 'dojo/_base/array', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'ngw-compulink-libs/dgrid-0.4.0/dstore/Rest', 'ngw-compulink-libs/dgrid-0.4.0/dgrid/OnDemandGrid', 'ngw-compulink-libs/dgrid-0.4.0/dgrid/Ke...
}, this.domNode); } }); });
new (declare([OnDemandGrid, Keyboard, Selection, EditorRelation]))({ collection: districtsStore, columns: this.config
random_line_split
slogging.py
from ethereum.utils import bcolors, is_numeric DEFAULT_LOGLEVEL = 'INFO' JSON_FORMAT = '%(message)s' PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s' FILE_PREFIX = '%(asctime)s' TRACE = 5 known_loggers = set() log_listeners = [] def _inject_into_logger(name, code, namespace=None): # This is a hack to f...
import logging import json import textwrap from json.encoder import JSONEncoder from logging import StreamHandler, Formatter, FileHandler
random_line_split
slogging.py
import logging import json import textwrap from json.encoder import JSONEncoder from logging import StreamHandler, Formatter, FileHandler from ethereum.utils import bcolors, is_numeric DEFAULT_LOGLEVEL = 'INFO' JSON_FORMAT = '%(message)s' PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s' FILE_PREFIX = '%(asctime...
eval( compile( code, logging._srcfile, 'exec' ), namespace ) setattr(logging.Logger, name, namespace[name]) # Add `trace()` level to Logger _inject_into_logger( 'trace', textwrap.dedent( """\ def trace(self, msg, *args, *...
namespace = {}
conditional_block
slogging.py
import logging import json import textwrap from json.encoder import JSONEncoder from logging import StreamHandler, Formatter, FileHandler from ethereum.utils import bcolors, is_numeric DEFAULT_LOGLEVEL = 'INFO' JSON_FORMAT = '%(message)s' PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s' FILE_PREFIX = '%(asctime...
trace = lambda self, *args, **kwargs: self._proxy('trace', *args, **kwargs) debug = lambda self, *args, **kwargs: self._proxy('debug', *args, **kwargs) info = lambda self, *args, **kwargs: self._proxy('info', *args, **kwargs) warn = warning = lambda self, *args, **kwargs: self._proxy('warning', *args,...
context = self.context.copy() context.update(kwargs) return getattr(self.logger, method_name)(*args, **context)
identifier_body
slogging.py
import logging import json import textwrap from json.encoder import JSONEncoder from logging import StreamHandler, Formatter, FileHandler from ethereum.utils import bcolors, is_numeric DEFAULT_LOGLEVEL = 'INFO' JSON_FORMAT = '%(message)s' PRINT_FORMAT = '%(levelname)s:%(name)s\t%(message)s' FILE_PREFIX = '%(asctime...
(logging.Logger): def __init__(self, name, level=DEFAULT_LOGLEVEL): self.warn = self.warning super(SLogger, self).__init__(name, level=level) @property def log_json(self): return SLogger.manager.log_json def is_active(self, level_name='trace'): return self.isEnabledFor...
SLogger
identifier_name
errors.rs
use attaca::marshal::ObjectHash;
types { Error, ErrorKind, ResultExt, Result; } links { Attaca(::attaca::Error, ::attaca::ErrorKind); } foreign_links { Clap(::clap::Error); Fmt(::std::fmt::Error); GlobSet(::globset::Error); Nul(::std::ffi::NulError); Io(::std::io::Error); } err...
error_chain! {
random_line_split
utils.py
# Copyright 2015 Google Inc. 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 required by applicable law or agr...
try: with open(os.path.expanduser(FLAGS.openstack_password_file)) as pwfile: password = pwfile.readline().rstrip() return password except IOError as e: raise Exception(error_msg + ' ' + str(e)) raise Exception(error_msg) def __init__(self): from novacl...
return password
conditional_block
utils.py
# Copyright 2015 Google Inc. 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 required by applicable law or agr...
""" Usage example: auth = KeystoneAuth(auth_url, auth_tenant, auth_user, auth_password) token = auth.get_token() tenant_id = auth.get_tenant_id() token and tenant_id are required to use all OpenStack python clients """ def __init__(self, url, tenant, user, password)...
class KeystoneAuth(object):
random_line_split
utils.py
# Copyright 2015 Google Inc. 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 required by applicable law or agr...
(self): if self.__connection is None: self.__authenticate() return self.__connection def __authenticate(self): import keystoneclient.v2_0.client as ksclient self.__connection = ksclient.Client( auth_url=self.__url, username=self.__user, ...
GetConnection
identifier_name
utils.py
# Copyright 2015 Google Inc. 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 required by applicable law or agr...
return decor return decored
from novaclient.exceptions import Unauthorized try: return function(*args, **kwargs) except Unauthorized as e: NovaClient.instance.reconnect() raise AuthException(str(e))
identifier_body
rprocess.py
"""Definitions for the `RProcess` class.""" from math import isnan import numpy as np from astrocats.catalog.source import SOURCE from mosfit.constants import C_CGS, DAY_CGS, IPI, KM_CGS, M_SUN_CGS from mosfit.modules.engines.engine import Engine from scipy.interpolate import RegularGridInterpolator # Important: Onl...
luminosities = [0.0 if isnan(x) else x for x in luminosities] return {self.dense_key('luminosities'): luminosities}
random_line_split
rprocess.py
"""Definitions for the `RProcess` class.""" from math import isnan import numpy as np from astrocats.catalog.source import SOURCE from mosfit.constants import C_CGS, DAY_CGS, IPI, KM_CGS, M_SUN_CGS from mosfit.modules.engines.engine import Engine from scipy.interpolate import RegularGridInterpolator # Important: Onl...
(Engine): """r-process decay engine. input luminosity adapted from Metzger 2016: 2017LRR....20....3M """ _REFERENCES = [ {SOURCE.BIBCODE: '2013ApJ...775...18B'}, {SOURCE.BIBCODE: '2017LRR....20....3M'}, {SOURCE.BIBCODE: '2017arXiv170708132V'} ] ckm = C_CGS / KM_CGS ...
RProcess
identifier_name
rprocess.py
"""Definitions for the `RProcess` class.""" from math import isnan import numpy as np from astrocats.catalog.source import SOURCE from mosfit.constants import C_CGS, DAY_CGS, IPI, KM_CGS, M_SUN_CGS from mosfit.modules.engines.engine import Engine from scipy.interpolate import RegularGridInterpolator # Important: Onl...
def process(self, **kwargs): """Process module.""" self._times = kwargs[self.key('dense_times')] self._mass = kwargs[self.key('mejecta')] * M_SUN_CGS self._rest_texplosion = kwargs[self.key('resttexplosion')] self._vejecta = kwargs[self.key('vejecta')] self._a = sel...
"""Initialize module.""" super(RProcess, self).__init__(**kwargs) self._wants_dense = True barnes_v = np.asarray([0.1, 0.2, 0.3]) barnes_M = np.asarray([1.e-3, 5.e-3, 1.e-2, 5.e-2]) barnes_a = np.asarray([[2.01, 4.52, 8.16], [0.81, 1.9, 3.2], [ 0.56,...
identifier_body
base.py
__author__ = 'Robbert Harms' __date__ = "2015-04-23" __maintainer__ = "Robbert Harms" __email__ = "robbert.harms@maastrichtuniversity.nl" class DVS(object): def __init__(self, comments, dvs_tables): """Create a new DVS object Args: comments (str): The list with comments on top of the...
return s
s = s.replace("\n", "\r\n")
conditional_block
base.py
__author__ = 'Robbert Harms' __date__ = "2015-04-23" __maintainer__ = "Robbert Harms" __email__ = "robbert.harms@maastrichtuniversity.nl" class DVS(object): def __init__(self, comments, dvs_tables): """Create a new DVS object Args: comments (str): The list with comments on top of the...
(self, windows_line_endings=True): """Get a complete string representation of the DVS. Args: windows_line_endings (boolean): If we want to include an \r before every \n """ s = self.comments + "\n" s += "\n".join([table.get_file_string(windows_line_endings=False) for...
get_file_string
identifier_name
base.py
__author__ = 'Robbert Harms' __date__ = "2015-04-23" __maintainer__ = "Robbert Harms" __email__ = "robbert.harms@maastrichtuniversity.nl" class DVS(object): def __init__(self, comments, dvs_tables): """Create a new DVS object Args: comments (str): The list with comments on top of the...
self.comments = comments self.dvs_tables = dvs_tables def get_file_string(self, windows_line_endings=True): """Get a complete string representation of the DVS. Args: windows_line_endings (boolean): If we want to include an \r before every \n """ s = self...
Attributes: comments (str): The list with comments on top of the file dvs_tables (list of DVSDirectionTable): The list with the direction tables """
random_line_split
base.py
__author__ = 'Robbert Harms' __date__ = "2015-04-23" __maintainer__ = "Robbert Harms" __email__ = "robbert.harms@maastrichtuniversity.nl" class DVS(object): def __init__(self, comments, dvs_tables): """Create a new DVS object Args: comments (str): The list with comments on top of the...
"""Get a complete string representation of this direction table. Args: windows_line_endings (boolean): If we want to include an \r before every \n """ s = self.comments s += '[directions={}]'.format(self.table.shape[0]) + "\n" s += 'CoordinateSystem = {}'.format(self...
identifier_body
server.js
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var util = require('util'); var browserSync = require('browser-sync'); var middleware = require('./proxy'); function browserSyncInit(baseDir, files, browser)
gulp.task('serve', ['watch'], function () { browserSyncInit([ paths.tmp + '/serve', paths.src, paths.lib ], [ paths.tmp + '/serve/app/**/*.css', paths.src + '/app/**/*.js', paths.lib + '/**/*.js', paths.src + 'src/assets/images/**/*', paths.tmp + '/serve/*.html', paths.tmp + '/...
{ browser = browser === undefined ? 'default' : browser; var routes = null; if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) { routes = { '/bower_components': 'bower_components' }; } browserSync.instance = browserSync.init(files, { startPath: '/', ...
identifier_body
server.js
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var util = require('util'); var browserSync = require('browser-sync'); var middleware = require('./proxy'); function browserSyncInit(baseDir, files, browser) { browser = browser === undefined ? 'default' : browser; var routes = null; if(base...
browserSync.instance = browserSync.init(files, { startPath: '/', server: { baseDir: baseDir, middleware: middleware, routes: routes }, browser: browser }); } gulp.task('serve', ['watch'], function () { browserSyncInit([ paths.tmp + '/serve', paths.src, paths.lib ...
{ routes = { '/bower_components': 'bower_components' }; }
conditional_block
server.js
'use strict';
var gulp = require('gulp'); var paths = gulp.paths; var util = require('util'); var browserSync = require('browser-sync'); var middleware = require('./proxy'); function browserSyncInit(baseDir, files, browser) { browser = browser === undefined ? 'default' : browser; var routes = null; if(baseDir === paths....
random_line_split
server.js
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var util = require('util'); var browserSync = require('browser-sync'); var middleware = require('./proxy'); function
(baseDir, files, browser) { browser = browser === undefined ? 'default' : browser; var routes = null; if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) { routes = { '/bower_components': 'bower_components' }; } browserSync.instance = browserSync.init(file...
browserSyncInit
identifier_name
SessionStore.js
/* Copyright 2017 Vector Creations Ltd 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 to in writing, sof...
extends Store { constructor() { super(dis); // Initialise state this._state = INITIAL_STATE; } _update() { // Persist state to localStorage if (this._state.cachedPassword) { localStorage.setItem('mx_pass', this._state.cachedPassword); } else { ...
SessionStore
identifier_name
SessionStore.js
/* Copyright 2017 Vector Creations Ltd 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 to in writing, sof...
* * Usage: * ``` * sessionStore.addListener(() => { * this.setState({ cachedPassword: sessionStore.getCachedPassword() }) * }) * ``` */ class SessionStore extends Store { constructor() { super(dis); // Initialise state this._state = INITIAL_STATE; } _update() { ...
* listeners (views) of state changes.
random_line_split
SessionStore.js
/* Copyright 2017 Vector Creations Ltd 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 to in writing, sof...
__onDispatch(payload) { switch (payload.action) { case 'cached_password': this._setState({ cachedPassword: payload.cachedPassword, }); break; case 'password_changed': this._setState({ ...
{ this._state = Object.assign(this._state, newState); this._update(); }
identifier_body
SessionStore.js
/* Copyright 2017 Vector Creations Ltd 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 to in writing, sof...
this.__emitChange(); } _setState(newState) { this._state = Object.assign(this._state, newState); this._update(); } __onDispatch(payload) { switch (payload.action) { case 'cached_password': this._setState({ cachedPassword...
{ localStorage.removeItem('mx_pass', this._state.cachedPassword); }
conditional_block
mod.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. //! OS abstractions for `Telemetry`. mod centos; mod debian; mod fedora; mod f...
() -> Result<Box<TelemetryProvider>> { if Centos::available() { Ok(Box::new(Centos)) } else if Debian::available() { Ok(Box::new(Debian)) } else if Fedora::available() { Ok(Box::new(Fedora)) } else if Freebsd::available() { Ok(Box::new(Freebsd)) } else...
factory
identifier_name
mod.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. //! OS abstractions for `Telemetry`. mod centos; mod debian; mod fedora; mod f...
if Centos::available() { Ok(Box::new(Centos)) } else if Debian::available() { Ok(Box::new(Debian)) } else if Fedora::available() { Ok(Box::new(Fedora)) } else if Freebsd::available() { Ok(Box::new(Freebsd)) } else if Macos::available() { Ok(Box...
} #[doc(hidden)] pub fn factory() -> Result<Box<TelemetryProvider>> {
random_line_split
mod.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. //! OS abstractions for `Telemetry`. mod centos; mod debian; mod fedora; mod f...
{ if Centos::available() { Ok(Box::new(Centos)) } else if Debian::available() { Ok(Box::new(Debian)) } else if Fedora::available() { Ok(Box::new(Fedora)) } else if Freebsd::available() { Ok(Box::new(Freebsd)) } else if Macos::available() { Ok(B...
identifier_body
Helpers.API.Establishments.js
(function (exports, $) { const Module = exports.Helpers.API || {} // Internal cache let internalCache = {} let formControls // Default config const settings = { // This is the ajax config object ajax: { url: '/establishments.json', type: 'GET', dataType: 'json' }, // Th...
(ajaxConfig) { // This module is a simple cache of data // It will self init and publish success and failure // events when the promise resolves return query(ajaxConfig).then(function (results) { // Load the results into the internal cache internalCache = results.sort(function (a, b) { ...
loadData
identifier_name
Helpers.API.Establishments.js
(function (exports, $) { const Module = exports.Helpers.API || {} // Internal cache let internalCache = {} let formControls // Default config const settings = { // This is the ajax config object ajax: { url: '/establishments.json', type: 'GET', dataType: 'json' }, // Th...
return 0 }) // Publish the success event $.publish(settings.events.cacheLoaded) }, function (status, error) { // Load the error status and response // in the the internal cache internalCache = { error: error, status: status } // Publish the ...
{ return 1 }
conditional_block
Helpers.API.Establishments.js
(function (exports, $) { const Module = exports.Helpers.API || {} // Internal cache let internalCache = {} let formControls // Default config const settings = { // This is the ajax config object ajax: { url: '/establishments.json', type: 'GET', dataType: 'json' }, // Th...
events: { cacheLoaded: '/API/establishments/loaded/', cacheLoadError: '/API/establishments/load/error/' } } // Init function loadData (ajaxConfig) { // This module is a simple cache of data // It will self init and publish success and failure // events when the promise resolves ...
dataAttr: 'featureDistance' }, // Success / Fail events via $.publish()
random_line_split
Helpers.API.Establishments.js
(function (exports, $) { const Module = exports.Helpers.API || {} // Internal cache let internalCache = {} let formControls // Default config const settings = { // This is the ajax config object ajax: { url: '/establishments.json', type: 'GET', dataType: 'json' }, // Th...
// leaving in place for possible refactor function getAsSelectWithOptions (a, b) { return getAsOptions(a, b) } // This method will return an array of <option> tags // It is also wrapped in a promise to ensure // the entire operation completes before other // events are triggered function getAsOpt...
{ // Checking DOM for feature flag value if ($(settings.init.selector).data(settings.init.dataAttr)) { formControls = moj.Helpers.FormControls return loadData() } }
identifier_body
geonetwork.py
import os import csv import tempfile import codecs from urlparse import urlsplit from shutil import abspath import requests from metadown.utils.etree import etree namespaces = { "gmx": "http://www.isotc211.org/2005/gmx", "gsr": "http://www.isotc211.org/2005/gsr", "gss": "http://www.isotc211.org/2005/gss"...
(self): isos = [] o, t = tempfile.mkstemp() with codecs.open(t, "w+", "utf-8") as h: h.write(requests.get(self.data).text) with codecs.open(t, "rb", "utf-8") as f: reader = csv.DictReader(self.utf_8_encoder(f)) for row in reader: if...
run
identifier_name
geonetwork.py
import os import csv import tempfile import codecs from urlparse import urlsplit from shutil import abspath import requests from metadown.utils.etree import etree namespaces = { "gmx": "http://www.isotc211.org/2005/gmx", "gsr": "http://www.isotc211.org/2005/gsr", "gss": "http://www.isotc211.org/2005/gss"...
yield line.encode('utf-8') def run(self): isos = [] o, t = tempfile.mkstemp() with codecs.open(t, "w+", "utf-8") as h: h.write(requests.get(self.data).text) with codecs.open(t, "rb", "utf-8") as f: reader = csv.DictReader(self.utf_8_encoder(f)...
# change to use ISO with extra GeoNetwork metadata self.download = base_url + '/srv/en/xml.metadata.get?id=' def utf_8_encoder(self, unicode_csv_data): for line in unicode_csv_data:
random_line_split
geonetwork.py
import os import csv import tempfile import codecs from urlparse import urlsplit from shutil import abspath import requests from metadown.utils.etree import etree namespaces = { "gmx": "http://www.isotc211.org/2005/gmx", "gsr": "http://www.isotc211.org/2005/gsr", "gss": "http://www.isotc211.org/2005/gss"...
@staticmethod def modifier(url, **kwargs): # translate ISO19139 to ISO19115 gmi_ns = "http://www.isotc211.org/2005/gmi" etree.register_namespace("gmi",gmi_ns) new_root = etree.Element("{%s}MI_Metadata" % gmi_ns) old_root = etree.parse(url).getroot() # carry ov...
root = etree.parse(url).getroot() x_res = root.xpath( '/gmd:MD_Metadata/gmd:fileIdentifier/gco:CharacterString', namespaces=namespaces ) uuid = "GeoNetwork-" + x_res[0].text + ".xml" return uuid
identifier_body
geonetwork.py
import os import csv import tempfile import codecs from urlparse import urlsplit from shutil import abspath import requests from metadown.utils.etree import etree namespaces = { "gmx": "http://www.isotc211.org/2005/gmx", "gsr": "http://www.isotc211.org/2005/gsr", "gss": "http://www.isotc211.org/2005/gss"...
def run(self): isos = [] o, t = tempfile.mkstemp() with codecs.open(t, "w+", "utf-8") as h: h.write(requests.get(self.data).text) with codecs.open(t, "rb", "utf-8") as f: reader = csv.DictReader(self.utf_8_encoder(f)) for row in reader: ...
yield line.encode('utf-8')
conditional_block
bootstrap-collapse.js
/* ============================================================= * bootstrap-collapse.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "Lic...
} /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = typeof option == 'object' && option if (!data) $this.dat...
, toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() }
random_line_split
Client.js
const uuid = require('uuid/v4') const zmq = require('zeromq') const events = require('events') const Handle = function (id, callback) { this.id = id this.callback = callback } Handle.prototype = Object.create(events.EventEmitter.prototype) /** * A client submits tasks to a broker. */ const Client = function (o...
, _addHandle (id, callback) { const handle = new Handle(id, callback) this.handles[id] = handle return handle }, _removeHandle (handle) { delete this.handles[handle.id] } }) module.exports = Client
{ return this.handles[id] }
identifier_body
Client.js
const uuid = require('uuid/v4') const zmq = require('zeromq') const events = require('events') const Handle = function (id, callback) { this.id = id this.callback = callback } Handle.prototype = Object.create(events.EventEmitter.prototype) /** * A client submits tasks to a broker. */ const Client = function (o...
if (handle.listeners('error').length !== 0) { handle.emit('error', task.data) } this._removeHandle(handle) }, _getHandle (id) { return this.handles[id] }, _addHandle (id, callback) { const handle = new Handle(id, callback) this.handles[id] = handle return handle }, _removeHandle (handl...
{ handle.callback(task.data) }
conditional_block
Client.js
const uuid = require('uuid/v4') const zmq = require('zeromq') const events = require('events') const Handle = function (id, callback) { this.id = id this.callback = callback } Handle.prototype = Object.create(events.EventEmitter.prototype) /** * A client submits tasks to a broker. */ const Client = function (o...
(task) { const handle = this._getHandle(task.id) if (typeof handle.callback === 'function') { handle.callback(task.data) } if (handle.listeners('error').length !== 0) { handle.emit('error', task.data) } this._removeHandle(handle) }, _getHandle (id) { return this.handles[id] }, _addHan...
_failed
identifier_name
Client.js
const uuid = require('uuid/v4') const zmq = require('zeromq') const events = require('events') const Handle = function (id, callback) { this.id = id this.callback = callback } Handle.prototype = Object.create(events.EventEmitter.prototype) /** * A client submits tasks to a broker. */ const Client = function (o...
_message (...args) { const adjustedLength = Math.max(args.length, 1) const payload = args[adjustedLength - 1] const task = JSON.parse(payload) switch (task.response) { case 'submitted': this._submitted(task) break case 'completed': this._completed(task) bre...
},
random_line_split
regions-mock-tcx.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 ...
(ty_arena: &'tcx Arena, ast_arena: &'ast Arena) -> TypeContext<'tcx, 'ast> { TypeContext { ty_arena: ty_arena, types: ~[], type_table: HashMap::new(), ast_arena: ast_arena, ast_counter: 0 } } fn add_type...
new
identifier_name
regions-mock-tcx.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 ...
} pub fn main() { let ty_arena = arena::Arena::new(); let ast_arena = arena::Arena::new(); let mut tcx = TypeContext::new(&ty_arena, &ast_arena); let ast = tcx.ast(ExprInt); let ty = compute_types(&mut tcx, ast); assert_eq!(*ty, TypeInt); }
}
random_line_split
regions-mock-tcx.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 ...
ExprLambda(ast) => { let arg_ty = tcx.add_type(TypeInt); let body_ty = compute_types(tcx, ast); let lambda_ty = tcx.add_type(TypeFunction(arg_ty, body_ty)); tcx.set_type(ast.id, lambda_ty) } } } pub fn main() { let ty_arena = arena::Arena::new();...
{ let ty = tcx.add_type(TypeInt); tcx.set_type(ast.id, ty) }
conditional_block
2357b6b3d76_.py
"""empty message Revision ID: 2357b6b3d76 Revises: fecca96b9d Create Date: 2015-10-27 10:26:52.074526 """ # revision identifiers, used by Alembic. revision = '2357b6b3d76' down_revision = 'fecca96b9d' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please...
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('citizen_complaints', 'source') op.drop_column('citizen_complaints', 'service_type') ### end Alembic commands ###
op.add_column('citizen_complaints', sa.Column('service_type', sa.String(length=255), nullable=True)) op.add_column('citizen_complaints', sa.Column('source', sa.String(length=255), nullable=True)) ### end Alembic commands ###
identifier_body
2357b6b3d76_.py
"""empty message Revision ID: 2357b6b3d76 Revises: fecca96b9d Create Date: 2015-10-27 10:26:52.074526 """ # revision identifiers, used by Alembic. revision = '2357b6b3d76' down_revision = 'fecca96b9d' from alembic import op import sqlalchemy as sa def
(): ### commands auto generated by Alembic - please adjust! ### op.add_column('citizen_complaints', sa.Column('service_type', sa.String(length=255), nullable=True)) op.add_column('citizen_complaints', sa.Column('source', sa.String(length=255), nullable=True)) ### end Alembic commands ### def downgrade...
upgrade
identifier_name
2357b6b3d76_.py
"""empty message Revision ID: 2357b6b3d76
""" # revision identifiers, used by Alembic. revision = '2357b6b3d76' down_revision = 'fecca96b9d' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('citizen_complaints', sa.Column('service_type', sa.String(length=255), n...
Revises: fecca96b9d Create Date: 2015-10-27 10:26:52.074526
random_line_split
RegressionFunction.js
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]} clover.pageData = {"classes":[{"el":119,"id":216512,"methods":[{"el":48,"sc":2,"sl":47},{"el":53,"sc":2,"sl":50},{"el":58,"sc":2,"sl":55},{"el":62,"sc":2,"sl":60},{"el":66,"sc":2,"sl":64},{"el":71,"sc":2,"sl":68},{"el":76,"sc":2,"sl":73},{"el":8...
random_line_split
install-plugins.ts
import { reporter } from "./utils/reporter" import path from "path" import { PluginConfigMap } from "." import { requireResolve } from "./utils/require-utils" const resolveGatsbyPath = (rootPath: string): string | never => { try { const gatsbyPath = requireResolve(`gatsby/package.json`, { paths: [rootPath]...
{ try { const gatsbyPath = resolveGatsbyPath(rootPath) const installPluginCommand = resolveGatsbyCliPath(rootPath, gatsbyPath) await addPluginsToProject( installPluginCommand, plugins, pluginOptions, rootPath, packages ) } catch (e) { reporter.error((e as Error).me...
identifier_body
install-plugins.ts
import { reporter } from "./utils/reporter" import path from "path" import { PluginConfigMap } from "." import { requireResolve } from "./utils/require-utils" const resolveGatsbyPath = (rootPath: string): string | never => { try { const gatsbyPath = requireResolve(`gatsby/package.json`, { paths: [rootPath]...
( plugins: Array<string>, pluginOptions: PluginConfigMap = {}, rootPath: string, packages: Array<string> ): Promise<void> { try { const gatsbyPath = resolveGatsbyPath(rootPath) const installPluginCommand = resolveGatsbyCliPath(rootPath, gatsbyPath) await addPluginsToProject( installPluginCo...
installPlugins
identifier_name
install-plugins.ts
import { reporter } from "./utils/reporter" import path from "path" import { PluginConfigMap } from "." import { requireResolve } from "./utils/require-utils" const resolveGatsbyPath = (rootPath: string): string | never => { try { const gatsbyPath = requireResolve(`gatsby/package.json`, { paths: [rootPath]...
return installPluginCommand } catch (e) { throw new Error( `Could not find a suitable version of gatsby-cli. Please report this issue at https://www.github.com/gatsbyjs/gatsby/issues` ) } } const addPluginsToProject = async ( installPluginCommand: string, plugins: Array<string>, pluginOpt...
{ throw new Error() }
conditional_block
install-plugins.ts
import { reporter } from "./utils/reporter" import path from "path" import { PluginConfigMap } from "." import { requireResolve } from "./utils/require-utils" const resolveGatsbyPath = (rootPath: string): string | never => { try { const gatsbyPath = requireResolve(`gatsby/package.json`, { paths: [rootPath]...
try { installPluginCommand = requireResolve( `gatsby-cli/lib/handlers/plugin-add`, { // Try to find gatsby-cli in the site root, or in the site's gatsby dir paths: [rootPath, path.dirname(gatsbyPath)], } ) } catch (e) { // We'll error out later }...
random_line_split
unix.rs
use super::RW; use super::evented::{Evented, EventedImpl, MioAdapter}; use std::io; use std::path::Path; use std::os::unix::io::RawFd; use mio_orig; /// Unix pipe reader pub type PipeReader = MioAdapter<mio_orig::unix::PipeReader>; /// Unix pipe writer pub type PipeWriter = MioAdapter<mio_orig::unix::PipeWriter>; //...
/// Try cloning the socket descriptor. pub fn try_clone(&self) -> io::Result<Self> { self.shared().io_ref().try_clone().map(MioAdapter::new) } } /// Unix socket pub type UnixSocket = MioAdapter<mio_orig::unix::UnixSocket>; impl UnixSocket { /// Returns a new, unbound, Unix domain socket ...
{ mio_orig::unix::UnixListener::bind(addr).map(MioAdapter::new) }
identifier_body
unix.rs
use super::RW; use super::evented::{Evented, EventedImpl, MioAdapter}; use std::io; use std::path::Path; use std::os::unix::io::RawFd; use mio_orig; /// Unix pipe reader pub type PipeReader = MioAdapter<mio_orig::unix::PipeReader>; /// Unix pipe writer pub type PipeWriter = MioAdapter<mio_orig::unix::PipeWriter>; //...
<P: AsRef<Path> + ?Sized>(self, addr: &P) -> io::Result<(UnixStream, bool)> { self.shared() .io_ref() .try_clone() .and_then(|t| mio_orig::unix::UnixSocket::connect(t, addr)) .map(|(t, b)| (MioAdapter::new(t), b)) } /// Bind the socket to the specified ad...
connect
identifier_name
unix.rs
use super::RW; use super::evented::{Evented, EventedImpl, MioAdapter}; use std::io; use std::path::Path; use std::os::unix::io::RawFd; use mio_orig; /// Unix pipe reader pub type PipeReader = MioAdapter<mio_orig::unix::PipeReader>; /// Unix pipe writer pub type PipeWriter = MioAdapter<mio_orig::unix::PipeWriter>; //...
pub fn connect<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<UnixStream> { mio_orig::unix::UnixStream::connect(path).map(MioAdapter::new) } /// Clone pub fn try_clone(&self) -> io::Result<Self> { self.shared().io_ref().try_clone().map(MioAdapter::new) } /// Try reading data ...
impl UnixStream { /// Connect UnixStream to `path`
random_line_split
gh-ed-editor.js
import Ember from 'ember'; import EditorAPI from 'ghost-admin/mixins/ed-editor-api'; import EditorShortcuts from 'ghost-admin/mixins/ed-editor-shortcuts'; import EditorScroll from 'ghost-admin/mixins/ed-editor-scroll'; import {invokeAction} from 'ember-invoke-action'; const {TextArea, run} = Ember; export default Tex...
run.scheduleOnce('afterRender', this, this.afterRenderEvent); }, afterRenderEvent() { if (this.get('focus') && this.get('focusCursorAtEnd')) { this.setSelection('end'); } }, actions: { toggleCopyHTMLModal(generatedHTML) { invokeAction(this, 'tog...
this._super(...arguments); this.setFocus(); invokeAction(this, 'setEditor', this);
random_line_split
gh-ed-editor.js
import Ember from 'ember'; import EditorAPI from 'ghost-admin/mixins/ed-editor-api'; import EditorShortcuts from 'ghost-admin/mixins/ed-editor-shortcuts'; import EditorScroll from 'ghost-admin/mixins/ed-editor-scroll'; import {invokeAction} from 'ember-invoke-action'; const {TextArea, run} = Ember; export default Tex...
}, actions: { toggleCopyHTMLModal(generatedHTML) { invokeAction(this, 'toggleCopyHTMLModal', generatedHTML); } } });
{ this.setSelection('end'); }
conditional_block
gh-ed-editor.js
import Ember from 'ember'; import EditorAPI from 'ghost-admin/mixins/ed-editor-api'; import EditorShortcuts from 'ghost-admin/mixins/ed-editor-shortcuts'; import EditorScroll from 'ghost-admin/mixins/ed-editor-scroll'; import {invokeAction} from 'ember-invoke-action'; const {TextArea, run} = Ember; export default Tex...
, afterRenderEvent() { if (this.get('focus') && this.get('focusCursorAtEnd')) { this.setSelection('end'); } }, actions: { toggleCopyHTMLModal(generatedHTML) { invokeAction(this, 'toggleCopyHTMLModal', generatedHTML); } } });
{ this._super(...arguments); this.setFocus(); invokeAction(this, 'setEditor', this); run.scheduleOnce('afterRender', this, this.afterRenderEvent); }
identifier_body
gh-ed-editor.js
import Ember from 'ember'; import EditorAPI from 'ghost-admin/mixins/ed-editor-api'; import EditorShortcuts from 'ghost-admin/mixins/ed-editor-shortcuts'; import EditorScroll from 'ghost-admin/mixins/ed-editor-scroll'; import {invokeAction} from 'ember-invoke-action'; const {TextArea, run} = Ember; export default Tex...
() { if (this.get('focus') && this.get('focusCursorAtEnd')) { this.setSelection('end'); } }, actions: { toggleCopyHTMLModal(generatedHTML) { invokeAction(this, 'toggleCopyHTMLModal', generatedHTML); } } });
afterRenderEvent
identifier_name
proxy.py
"""An HTTP proxy that supports IPv6 as well as the HTTP CONNECT method, among other things.""" # Standard libary imports import socket import thread import select __version__ = '0.1.0 Draft 1' BUFFER_LENGTH = 8192 VERSION = 'Python Proxy/{}'.format(__version__) HTTP_VERSION = 'HTTP/1.1' class ConnectionHandler(obje...
self.client.close() self.target.close() def start_server(host='localhost', port=8080, ipv_6=False, timeout=60, handler=ConnectionHandler): """Start the HTTP proxy server.""" if ipv_6: soc_type = socket.AF_INET6 else: soc_type = socket.AF_INET soc = soc...
count += 1 (recv, _, error) = select.select(socs, [], socs, 3) if error: break if recv: for in_ in recv: data = in_.recv(BUFFER_LENGTH) if in_ is self.client: out = self.target ...
conditional_block
proxy.py
"""An HTTP proxy that supports IPv6 as well as the HTTP CONNECT method, among other things.""" # Standard libary imports import socket import thread import select __version__ = '0.1.0 Draft 1' BUFFER_LENGTH = 8192 VERSION = 'Python Proxy/{}'.format(__version__) HTTP_VERSION = 'HTTP/1.1' class ConnectionHandler(obje...
def start_server(host='localhost', port=8080, ipv_6=False, timeout=60, handler=ConnectionHandler): """Start the HTTP proxy server.""" if ipv_6: soc_type = socket.AF_INET6 else: soc_type = socket.AF_INET soc = socket.socket(soc_type) soc.bind((host, port)) prin...
"""Read data from client connection and forward to server connection.""" time_out_max = self.timeout/3 socs = [self.client, self.target] count = 0 while 1: count += 1 (recv, _, error) = select.select(socs, [], socs, 3) if error: ...
identifier_body
proxy.py
"""An HTTP proxy that supports IPv6 as well as the HTTP CONNECT method, among other things.""" # Standard libary imports import socket import thread import select __version__ = '0.1.0 Draft 1' BUFFER_LENGTH = 8192 VERSION = 'Python Proxy/{}'.format(__version__) HTTP_VERSION = 'HTTP/1.1' class ConnectionHandler(obje...
soc.listen(0) while 1: thread.start_new_thread(handler, soc.accept()+(timeout,)) if __name__ == '__main__': start_server()
soc = socket.socket(soc_type) soc.bind((host, port)) print 'Serving on {0}:{1}.'.format(host, port)
random_line_split
proxy.py
"""An HTTP proxy that supports IPv6 as well as the HTTP CONNECT method, among other things.""" # Standard libary imports import socket import thread import select __version__ = '0.1.0 Draft 1' BUFFER_LENGTH = 8192 VERSION = 'Python Proxy/{}'.format(__version__) HTTP_VERSION = 'HTTP/1.1' class
(object): """Handles connections between the HTTP client and HTTP server.""" def __init__(self, connection, _, timeout): self.client = connection self.client_buffer = '' self.timeout = timeout self.target = None method, path, protocol = self.get_base_header() if m...
ConnectionHandler
identifier_name
matching.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/. */ //! High-level interface to CSS selector matching. #![allow(unsafe_code)] #![deny(missing_docs)] use context::{E...
let pseudo_styles = old_styles.pseudos.as_array().iter().zip( data.styles.pseudos.as_array().iter()); for (i, (old, new)) in pseudo_styles.enumerate() { match (old, new) { (&Some(ref old), &Some(ref new)) => { self.accumulate_dama...
}
random_line_split
matching.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/. */ //! High-level interface to CSS selector matching. #![allow(unsafe_code)] #![deny(missing_docs)] use context::{E...
} impl<E: TElement> PrivateMatchMethods for E {} /// The public API that elements expose for selector matching. pub trait MatchMethods : TElement { /// Returns the closest parent element that doesn't have a display: contents /// style (and thus generates a box). /// /// This is needed to correctly ha...
{ use animation::{self, Animation}; use dom::TNode; // Finish any expired transitions. let this_opaque = self.as_node().opaque(); animation::complete_expired_transitions(this_opaque, style, context); // Merge any running animations into the current style, and cancel the...
identifier_body
matching.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/. */ //! High-level interface to CSS selector matching. #![allow(unsafe_code)] #![deny(missing_docs)] use context::{E...
( &self, context: &mut StyleContext<Self>, old_values: &mut Option<Arc<ComputedValues>>, new_values: &mut Arc<ComputedValues>, restyle_hint: RestyleHint, important_rules_changed: bool, ) { use context::UpdateAnimationsTasks; if context.shared.traversa...
process_animations
identifier_name
serializers.py
from rest_framework.serializers import ( HyperlinkedIdentityField,
ModelSerializer, SerializerMethodField, ) from comments.api.serializers import CommentSerializer from accounts.api.serializers import UserDetailSerializer from comments.models import Comment from posts.models import Post class PostCreateUpdateSerializer(ModelSerializer): class Meta: model = Post fields = [ ...
random_line_split
serializers.py
from rest_framework.serializers import ( HyperlinkedIdentityField, ModelSerializer, SerializerMethodField, ) from comments.api.serializers import CommentSerializer from accounts.api.serializers import UserDetailSerializer from comments.models import Comment from posts.models import Post class PostCreateUpdateSer...
(self, obj): #content_type = obj.get_content_type #object_id = obj.id c_qs = Comment.objects.filter_by_instance(obj) comments = CommentSerializer(c_qs, many=True).data return comments class PostListSerializer(ModelSerializer): url = post_detail_url user = UserDetailSerializer(read_only=True) class Meta: ...
get_comments
identifier_name
serializers.py
from rest_framework.serializers import ( HyperlinkedIdentityField, ModelSerializer, SerializerMethodField, ) from comments.api.serializers import CommentSerializer from accounts.api.serializers import UserDetailSerializer from comments.models import Comment from posts.models import Post class PostCreateUpdateSer...
model = Post fields = [ 'url', 'user', 'title', 'slug', 'content', 'publish', ]
identifier_body
mod.rs
// we try to parse these as windows keycodes mod keys; pub use self::keys::Keys as Key; mod linux; mod qcode; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Modifier { Alt = 0x0001, Ctrl = 0x0002, Shift = 0x0004, Win = 0x0008, } const NOREPEAT: u32 = 0x4000; ...
else { if let Some(i) = self.modifiers.iter().position(|&x| x == m) { self.modifiers.swap_remove(i); } } } else if down { bindings.extend(self.bindings.iter().enumerate() .filter(...
{ if !self.modifiers.contains(&m) { self.modifiers.push(m); } }
conditional_block
mod.rs
// we try to parse these as windows keycodes mod keys; pub use self::keys::Keys as Key; mod linux; mod qcode; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Modifier { Alt = 0x0001, Ctrl = 0x0002, Shift = 0x0004, Win = 0x0008, } const NOREPEAT: u32 = 0x4000; ...
} } else if down { bindings.extend(self.bindings.iter().enumerate() .filter(|&(_, b)| b.matches(&self.modifiers, k)) .map(|(i, _)| i)); } KeyResolution { hotkeys: bindings...
random_line_split
mod.rs
// we try to parse these as windows keycodes mod keys; pub use self::keys::Keys as Key; mod linux; mod qcode; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum Modifier { Alt = 0x0001, Ctrl = 0x0002, Shift = 0x0004, Win = 0x0008, } const NOREPEAT: u32 = 0x4000; ...
(bindings: &'a [KeyBinding]) -> KeyboardState { KeyboardState { modifiers: Vec::new(), bindings, } } pub fn input_linux(&mut self, code: u32, down: bool) -> Option<KeyResolution> { linux::key_convert(code).map(|k| { let mut bindings = Vec::new(); ...
new
identifier_name
shopcustomers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") ...
from shop.models.customer import CustomerModel data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0) for customer in CustomerModel.objects.iterator(): data['total'] += 1 if customer.user.is_active: data['active'] += 1 ...
identifier_body
shopcustomers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") ...
elif customer.is_guest(): data['guests'] += 1 elif customer.is_anonymous(): data['anonymous'] += 1 if customer.is_expired(): data['expired'] += 1 if delete_expired: customer.delete() msg = _(...
data['registered'] += 1
conditional_block
shopcustomers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ class Command(BaseCommand): help = _("Collect information about all customers which accessed this shop.") ...
(self, verbosity, delete_expired, *args, **options): from shop.models.customer import CustomerModel data = dict(total=0, anonymous=0, active=0, staff=0, guests=0, registered=0, expired=0) for customer in CustomerModel.objects.iterator(): data['total'] += 1 if customer.use...
handle
identifier_name