file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
modelsHelper.py
import settings def db_connect(): """ Performs database connection using database settings from settings.py. :return: sqlalchemy engine instance """ # return create_engine('sqlite:///images.db', echo=True) return create_engine('{drivername}://{username}:{password}@{host}:{port}/{datab...
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import as_declarative
random_line_split
test_integration_tester.py
#!/usr/bin/env python # encoding: utf-8 """ Functional tests of the RabbitMQ Workers """ import mock import json import unittest import ADSDeploy.app as app from ADSDeploy.pipeline.workers import IntegrationTestWorker, \ DatabaseWriterWorker from ADSDeploy.webapp.views import MiniRabbit from ADSDeploy.models imp...
@mock.patch('ADSDeploy.pipeline.integration_tester.IntegrationTestWorker.run_test') def test_workflow_of_integration_worker(self, mock_run_test): """ General work flow of the integration worker from receiving a packet, to finishing with a packet. """ # Worker receives a...
with MiniRabbit(RABBITMQ_URL) as w: w.delete_queue('in', exchange='test') w.delete_queue('out', exchange='test') w.delete_queue('database', exchange='test') # Destroy database Base.metadata.drop_all() self.app.close_app()
identifier_body
test_integration_tester.py
#!/usr/bin/env python # encoding: utf-8 """ Functional tests of the RabbitMQ Workers """ import mock import json import unittest import ADSDeploy.app as app from ADSDeploy.pipeline.workers import IntegrationTestWorker, \ DatabaseWriterWorker from ADSDeploy.webapp.views import MiniRabbit from ADSDeploy.models imp...
# Push to rabbitmq with MiniRabbit(RABBITMQ_URL) as w: w.publish(route='in', exchange='test', payload=json.dumps(packet)) test_worker = IntegrationTestWorker(params=params) test_worker.run() test_worker.connection.close() # Assert there is a packet on the pu...
'status': 'database', 'TEST_RUN': True }
random_line_split
test_integration_tester.py
#!/usr/bin/env python # encoding: utf-8 """ Functional tests of the RabbitMQ Workers """ import mock import json import unittest import ADSDeploy.app as app from ADSDeploy.pipeline.workers import IntegrationTestWorker, \ DatabaseWriterWorker from ADSDeploy.webapp.views import MiniRabbit from ADSDeploy.models imp...
(self): # Create queue with MiniRabbit(RABBITMQ_URL) as w: w.make_queue('in', exchange='test') w.make_queue('out', exchange='test') w.make_queue('database', exchange='test') # Create database app.init_app({ 'SQLALCHEMY_URL': 'sqlite://', ...
setUp
identifier_name
test_integration_tester.py
#!/usr/bin/env python # encoding: utf-8 """ Functional tests of the RabbitMQ Workers """ import mock import json import unittest import ADSDeploy.app as app from ADSDeploy.pipeline.workers import IntegrationTestWorker, \ DatabaseWriterWorker from ADSDeploy.webapp.views import MiniRabbit from ADSDeploy.models imp...
self.assertEqual(deployment.tested, True)
self.assertEqual( packet[key], getattr(deployment, key) )
conditional_block
docker.py
# # Copyright 2021 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
(): """ Stop all containers. """ common.run_local_cmd('docker stop $(docker ps -a -q)') time.sleep(await_seconds) def remove_all_docker_containers(): """ Remove all containers. """ common.run_local_cmd('docker rm $(docker ps -a -q)') time.sleep(await_seconds)
stop_all_docker_containers
identifier_name
docker.py
# # Copyright 2021 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
'name': name, 'netns': docker_pid, 'pid': docker_pid, 'ip_addr': container_port_ip_addr, 'eth_addr': container_port_eth_addr, 'port_name': port_name, 'command': command } return ret def connect(node_a, node_b): """ Setup the IP route and...
print(common.get_container_port_ether(str(docker_pid), port_name)) exit() # Store the configuration. ret = {
random_line_split
docker.py
# # Copyright 2021 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
# Get port ip and ethernet address. port_ip_addr = common.run_local_cmd( common.get_port_ip(port_name), get_output=True) port_eth_addr = common.run_local_cmd( common.get_port_ether(port_name), get_output=True) # Verify port is setup with a valid ip and ethernet address. if not com...
print('KNI {} not up'.format(port_name)) exit()
conditional_block
docker.py
# # Copyright 2021 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
def stop_all_docker_containers(): """ Stop all containers. """ common.run_local_cmd('docker stop $(docker ps -a -q)') time.sleep(await_seconds) def remove_all_docker_containers(): """ Remove all containers. """ common.run_local_cmd('docker rm $(docker ps -a -q)')...
""" Return the count of running containers. """ n_docker = common.run_local_cmd('expr $(docker ps -a | wc -l) - 1', get_output=True) return int(n_docker)
identifier_body
app.js
'use strict'; /** * @ngdoc overview * @name commentApp * @description * # commentApp * * Main module of the application. */ angular.module('commentApp', ['ui.router']) .constant('commentCfg', commentCfg) .config(['$stateProvider', function ($stateProvider) { if (commentCfg.applicationPath === undefined) { ...
});
random_line_split
app.js
'use strict'; /** * @ngdoc overview * @name commentApp * @description * # commentApp * * Main module of the application. */ angular.module('commentApp', ['ui.router']) .constant('commentCfg', commentCfg) .config(['$stateProvider', function ($stateProvider) { if (commentCfg.applicationPath === undefined)
$stateProvider .state('login', { templateUrl: commentCfg.applicationPath + 'views/login.html', controller: 'LoginCtrl' }) .state('main', { templateUrl: commentCfg.applicationPath + 'views/main.html', controller: 'MainCtrl', resolve: { auth: ['authService', function (authService) { ...
{ console.log('Missing configuration for "applicationPath", fallback to empty value!'); commentCfg.applicationPath = ''; }
conditional_block
CollisionDetector.js
import EndOfGameEvent from "../events/EndOfGameEvent"; import ExitLevelEvent from "../events/ExitLevelEvent"; class CollisionDetector { constructor(scoreMgr) { this.scoreManager = scoreMgr; } detectAll(hero, level)
// Detects collisions with platforms level.platforms.getChildren().forEach(function(platform){ // We're interested in collisions that: // 1. Actually occurs (detectCollision(a, b) is true) // 2. Player is over the platform (hero.getY() < platform.getY()) ...
{ var that = this; var collided = false; // Detects collisions with enemies level.enemies.getChildren().forEach(function(enemy){ // There are two types of collisions with enemies: // 1. If player is falling (hero.ySpeed > 0 [1.a] // AND hero.ge...
identifier_body
CollisionDetector.js
import EndOfGameEvent from "../events/EndOfGameEvent"; import ExitLevelEvent from "../events/ExitLevelEvent"; class CollisionDetector {
(scoreMgr) { this.scoreManager = scoreMgr; } detectAll(hero, level) { var that = this; var collided = false; // Detects collisions with enemies level.enemies.getChildren().forEach(function(enemy){ // There are two types of collisions with enemies: ...
constructor
identifier_name
CollisionDetector.js
import EndOfGameEvent from "../events/EndOfGameEvent"; import ExitLevelEvent from "../events/ExitLevelEvent"; class CollisionDetector { constructor(scoreMgr) { this.scoreManager = scoreMgr; } detectAll(hero, level) { var that = this; var collided = false; // Detects colli...
&& hero.ySpeed >= 0) { // 3 hero.ySpeed *= hero.bounce; hero.counter = 0; hero.setY(platform.getY() - hero.getHeight()); } }); // Detects collisions with coins level.coins.getChildren().forEach(function(coi...
// 2. Player is over the platform (hero.getY() < platform.getY()) // 3. Player is falling over (hero.ySpeed > 0) if(that.detectCollision(platform, hero) // 1 && hero.getY() < platform.getY() // 2
random_line_split
CollisionDetector.js
import EndOfGameEvent from "../events/EndOfGameEvent"; import ExitLevelEvent from "../events/ExitLevelEvent"; class CollisionDetector { constructor(scoreMgr) { this.scoreManager = scoreMgr; } detectAll(hero, level) { var that = this; var collided = false; // Detects colli...
}); // Detects collisions with coins level.coins.getChildren().forEach(function(coin){ // Collisions with coins are straightforward: // it they occur, score is rewarded and coin // dissapears from stage. if(that.detectCollision(coin, hero)) { ...
{ // 3 hero.ySpeed *= hero.bounce; hero.counter = 0; hero.setY(platform.getY() - hero.getHeight()); }
conditional_block
views.py
""" See LICENSE file for copyright and license details. """ from app import app from flask import render_template, flash, redirect #from app.forms import LoginForm from app.modules.constant import * @app.route("/") @app.route("/index") @app.route("/index/") @app.route("/<app_profile>/index") @app.route...
""" Reads the text file and returns a list of lines. """ lines = [] with open(text_file, encoding='utf-8') as text: for line in text: lines.append(line.strip()) return lines
identifier_body
views.py
""" See LICENSE file for copyright and license details. """ from app import app from flask import render_template, flash, redirect #from app.forms import LoginForm from app.modules.constant import * @app.route("/") @app.route("/index") @app.route("/index/") @app.route("/<app_profile>/index") @app.route...
else: return render_template("404.html", title = '404') @app.route("/contact") @app.route("/contact/") @app.route("/<app_profile>/contact") @app.route("/<app_profile>/contact/") def contact(app_profile = AppProfile.PERSONAL): """ Address book. """ # Try to ...
return render_template("trading_journal.html", title = 'Trading Journal', user = user, app_profile = app_profile.lower())
conditional_block
views.py
""" See LICENSE file for copyright and license details. """ from app import app from flask import render_template, flash, redirect #from app.forms import LoginForm from app.modules.constant import * @app.route("/") @app.route("/index") @app.route("/index/") @app.route("/<app_profile>/index") @app.route...
return render_template("index.html", title = 'Central command entity', user = user, app_profile = app_profile.lower()) @app.route("/report_finance") @app.route("/report_finance/") @app.route("/<app_profile>/report_finance") @app.route("/<app_profile>/report_finance/") def report_fi...
if app_profile == '': app_profile = 'personal'
random_line_split
views.py
""" See LICENSE file for copyright and license details. """ from app import app from flask import render_template, flash, redirect #from app.forms import LoginForm from app.modules.constant import * @app.route("/") @app.route("/index") @app.route("/index/") @app.route("/<app_profile>/index") @app.route...
(app_profile = AppProfile.PERSONAL): """ Trading Journal """ if app_profile == AppProfile.ZIVLE: return render_template("trading_journal.html", title = 'Trading Journal', user = user, app_profile = app_profile.lower()) else: return re...
trading_journal
identifier_name
settings.py
""" Django settings for stompy project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # ...
# https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/'
# Static files (CSS, JavaScript, Images)
random_line_split
0007_auto_20140805_2253.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
field=models.CharField(blank=True, null=True, max_length=80), preserve_default=True, ), migrations.AddField( model_name='problem', name='time_limit', field=models.PositiveIntegerField(default=5), preserve_default=True, ), ...
dependencies = [ ('codecompetitions', '0006_auto_20140805_2234'), ] operations = [ migrations.AddField( model_name='problem', name='expected_output', field=models.TextField(default=''), preserve_default=False, ), migrations.AddFiel...
identifier_body
0007_auto_20140805_2253.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('codecompetitions', '0006_auto_20140805_2234'), ] operations = [ migrations.AddField( model_name='problem', ...
model_name='problem', name='time_limit', field=models.PositiveIntegerField(default=5), preserve_default=True, ), ]
random_line_split
0007_auto_20140805_2253.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
(migrations.Migration): dependencies = [ ('codecompetitions', '0006_auto_20140805_2234'), ] operations = [ migrations.AddField( model_name='problem', name='expected_output', field=models.TextField(default=''), preserve_default=False, ...
Migration
identifier_name
lock.py
# Copyright (c) 2019 PaddlePaddle 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 appli...
(file): raise NotImplementedError('Windows is not supported.') def unlock(file): raise NotImplementedError('Windows is not supported.') elif os.name == 'posix': from fcntl import flock, LOCK_EX, LOCK_UN def lock(file): """Lock the file in local file system.""" flock(file.f...
lock
identifier_name
lock.py
# Copyright (c) 2019 PaddlePaddle 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 appli...
raise RuntimeError("File Locker only support NT and Posix platforms!")
flock(file.fileno(), LOCK_UN) else:
random_line_split
lock.py
# Copyright (c) 2019 PaddlePaddle 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 appli...
def unlock(file): raise NotImplementedError('Windows is not supported.') elif os.name == 'posix': from fcntl import flock, LOCK_EX, LOCK_UN def lock(file): """Lock the file in local file system.""" flock(file.fileno(), LOCK_EX) def unlock(file): """Unlock the file in...
raise NotImplementedError('Windows is not supported.')
identifier_body
lock.py
# Copyright (c) 2019 PaddlePaddle 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 appli...
else: raise RuntimeError("File Locker only support NT and Posix platforms!")
from fcntl import flock, LOCK_EX, LOCK_UN def lock(file): """Lock the file in local file system.""" flock(file.fileno(), LOCK_EX) def unlock(file): """Unlock the file in local file system.""" flock(file.fileno(), LOCK_UN)
conditional_block
TabBarTabJQueryViewDescription.ts
// Module module TS.IJQuery.MVP.Tab { // Class export class TabBarTabJQueryViewDescription { public static tabBarTabJQueryViewDescriptionFactoryFromMap( tabBarIdsToViewDescriptions: { [_: string]: JQueryViewDescription; }, clickableElementSelector: string, styleable...
} else { result = null; } return result; } } // Constructor constructor( private _clickableElementSelector:string, private _styleableElementSelector:string, private _view:IJQueryView) { } public get...
random_line_split
TabBarTabJQueryViewDescription.ts
// Module module TS.IJQuery.MVP.Tab { // Class export class TabBarTabJQueryViewDescription { public static tabBarTabJQueryViewDescriptionFactoryFromMap( tabBarIdsToViewDescriptions: { [_: string]: JQueryViewDescription; }, clickableElementSelector: string, styleable...
(): string { return this._clickableElementSelector; } public getStyleableElementSelector(): string { return this._styleableElementSelector; } public getView(): IJQueryView { return this._view; } } }
getClickableElementSelector
identifier_name
TabBarTabJQueryViewDescription.ts
// Module module TS.IJQuery.MVP.Tab { // Class export class TabBarTabJQueryViewDescription { public static tabBarTabJQueryViewDescriptionFactoryFromMap( tabBarIdsToViewDescriptions: { [_: string]: JQueryViewDescription; }, clickableElementSelector: string, styleable...
else { result = null; } return result; } } // Constructor constructor( private _clickableElementSelector:string, private _styleableElementSelector:string, private _view:IJQueryView) { } public getClickableElementS...
{ var view = viewDescription.createView(container); result = new TabBarTabJQueryViewDescription(clickableElementSelector, styleableElementSelector, view); }
conditional_block
TabBarTabJQueryViewDescription.ts
// Module module TS.IJQuery.MVP.Tab { // Class export class TabBarTabJQueryViewDescription { public static tabBarTabJQueryViewDescriptionFactoryFromMap( tabBarIdsToViewDescriptions: { [_: string]: JQueryViewDescription; }, clickableElementSelector: string, styleable...
public getStyleableElementSelector(): string { return this._styleableElementSelector; } public getView(): IJQueryView { return this._view; } } }
{ return this._clickableElementSelector; }
identifier_body
config-model.js
var cdb = require('cartodb-deep-insights.js'); /** * Model for general frontend configuration. * Ported from old cdb.config, since we can't reuse the older model that's tied to v3 of cartodb.js * * Also, rather than putting it as a global object, it's intended to be instantiated at the entry point and passed as *...
return url; } });
url = this.get('sql_api_protocol') + '://' + this.get('user_name') + '.' + this.get('sql_api_domain') + ':' + this.get('sql_api_port'); }
conditional_block
config-model.js
var cdb = require('cartodb-deep-insights.js'); /** * Model for general frontend configuration. * Ported from old cdb.config, since we can't reuse the older model that's tied to v3 of cartodb.js * * Also, rather than putting it as a global object, it's intended to be instantiated at the entry point and passed as *...
*/ getSqlApiUrl: function (version) { version = version || 'v2'; return this._getSqlApiBaseUrl() + '/api/' + version + '/sql'; }, /** * @return {String} returns the base url to compose the final url, e.g. http://user.cartodb.com/ */ _getSqlApiBaseUrl: function () { var url; if (this.ge...
random_line_split
test_rbac_resolvers.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
def _insert_common_mock_resources(self): pack_1_db = PackDB(name='test_pack_1', ref='test_pack_1', description='', version='0.1.0', author='foo', email='test@example.com') pack_1_db = Pack.add_or_update(pack_1_db) self.resources['pack_1'] = pack_1_db pac...
user_1_db = UserDB(name='admin') user_1_db = User.add_or_update(user_1_db) self.users['admin'] = user_1_db user_2_db = UserDB(name='observer') user_2_db = User.add_or_update(user_2_db) self.users['observer'] = user_2_db user_3_db = UserDB(name='no_roles') user_3...
identifier_body
test_rbac_resolvers.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
return True def _insert_common_mocks(self): self._insert_common_mock_users() self._insert_common_mock_resources() self._insert_common_mock_roles() self._insert_common_mock_role_assignments() def _insert_common_mock_users(self): # Insert common mock users ...
return False
conditional_block
test_rbac_resolvers.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
grant_db = PermissionGrant.add_or_update(grant_db) permission_grants = [str(grant_db.id)] role_3_db = RoleDB(name='custom_role_pack_grant', permission_grants=permission_grants) role_3_db = Role.add_or_update(role_3_db) self.roles['custom_role_pack_grant'] = role_3_db def _in...
grant_db = PermissionGrantDB(resource_uid=self.resources['pack_1'].get_uid(), resource_type=ResourceType.PACK, permission_types=[PermissionType.PACK_CREATE])
random_line_split
test_rbac_resolvers.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
(self): expected_msg = 'Unsupported resource: alias' self.assertRaisesRegexp(ValueError, expected_msg, get_resolver_for_resource_type, resource_type='alias')
test_get_resolver_for_resource_type_unsupported_resource_type
identifier_name
3fab9480c190_professor_instructor.py
"""professor => instructor Revision ID: 3fab9480c190 Revises: 31ded1f6ad6 Create Date: 2014-02-17 00:56:12.566690 """ # revision identifiers, used by Alembic. revision = '3fab9480c190' down_revision = '31ded1f6ad6' from alembic import op import sqlalchemy as sa metadata = sa.MetaData() role = sa.Table('Role', meta...
update_stmt = role.update().where(role.c.name == 'instructor').values(name = 'professor') op.execute(update_stmt)
identifier_body
3fab9480c190_professor_instructor.py
"""professor => instructor Revision ID: 3fab9480c190 Revises: 31ded1f6ad6 Create Date: 2014-02-17 00:56:12.566690 """ # revision identifiers, used by Alembic. revision = '3fab9480c190' down_revision = '31ded1f6ad6' from alembic import op import sqlalchemy as sa metadata = sa.MetaData() role = sa.Table('Role', meta...
def downgrade(): update_stmt = role.update().where(role.c.name == 'instructor').values(name = 'professor') op.execute(update_stmt)
def upgrade(): update_stmt = role.update().where(role.c.name == 'professor').values(name = 'instructor') op.execute(update_stmt)
random_line_split
3fab9480c190_professor_instructor.py
"""professor => instructor Revision ID: 3fab9480c190 Revises: 31ded1f6ad6 Create Date: 2014-02-17 00:56:12.566690 """ # revision identifiers, used by Alembic. revision = '3fab9480c190' down_revision = '31ded1f6ad6' from alembic import op import sqlalchemy as sa metadata = sa.MetaData() role = sa.Table('Role', meta...
(): update_stmt = role.update().where(role.c.name == 'professor').values(name = 'instructor') op.execute(update_stmt) def downgrade(): update_stmt = role.update().where(role.c.name == 'instructor').values(name = 'professor') op.execute(update_stmt)
upgrade
identifier_name
clean.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re from ansible import constants as C from ansible....
if isinstance(dirty[k], (MutableMapping, MutableSequence)): strip_internal_keys(dirty[k], exceptions=exceptions) else: raise AnsibleError("Cannot strip invalid keys from %s" % type(dirty)) return dirty def remove_internal_keys(data): ''' More nuanced version of s...
del dirty[k] continue
conditional_block
clean.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re from ansible import constants as C from ansible....
def clean_facts(facts): ''' remove facts that can override internal keys or otherwise deemed unsafe ''' data = module_response_deepcopy(facts) remove_keys = set() fact_keys = set(data.keys()) # first we add all of our magic variable names to the set of # keys we want to remove from facts ...
''' More nuanced version of strip_internal_keys ''' for key in list(data.keys()): if (key.startswith('_ansible_') and key != '_ansible_parsed') or key in C.INTERNAL_RESULT_KEYS: display.warning("Removed unexpected internal key in module return: %s = %s" % (key, data[key])) de...
identifier_body
clean.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type
from ansible.errors import AnsibleError from ansible.module_utils import six from ansible.module_utils._text import to_text from ansible.module_utils.common._collections_compat import MutableMapping, MutableSequence from ansible.plugins.loader import connection_loader from ansible.utils.display import Display display ...
import os import re from ansible import constants as C
random_line_split
clean.py
# Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re from ansible import constants as C from ansible....
(dirty, exceptions=None): # All keys starting with _ansible_ are internal, so change the 'dirty' mapping and remove them. if exceptions is None: exceptions = tuple() if isinstance(dirty, MutableSequence): for element in dirty: if isinstance(element, (MutableMapping, MutableSeq...
strip_internal_keys
identifier_name
lib.rs
extern crate byteorder; extern crate bytes; extern crate tokio_io; use std::io; use tokio_io::codec::{Encoder, Decoder}; use bytes::BytesMut; mod error; mod qos; mod conn_return_code; mod header; mod packet_type; pub struct Mqtt{} impl Mqtt{ pub fn
() -> Mqtt{ Mqtt{} } } impl Decoder for Mqtt{ type Item = String; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<String>> { Err(io::Error::new(io::ErrorKind::Other, "Not implemented")) } } impl Encoder...
new
identifier_name
lib.rs
extern crate byteorder; extern crate bytes; extern crate tokio_io; use std::io; use tokio_io::codec::{Encoder, Decoder}; use bytes::BytesMut; mod error; mod qos; mod conn_return_code; mod header; mod packet_type; pub struct Mqtt{} impl Mqtt{ pub fn new() -> Mqtt{ Mqtt{} } }
type Item = String; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<String>> { Err(io::Error::new(io::ErrorKind::Other, "Not implemented")) } } impl Encoder for Mqtt { type Item = String; type Error = io::Error;...
impl Decoder for Mqtt{
random_line_split
lib.rs
extern crate byteorder; extern crate bytes; extern crate tokio_io; use std::io; use tokio_io::codec::{Encoder, Decoder}; use bytes::BytesMut; mod error; mod qos; mod conn_return_code; mod header; mod packet_type; pub struct Mqtt{} impl Mqtt{ pub fn new() -> Mqtt{ Mqtt{} } } impl Decoder for...
} impl Encoder for Mqtt { type Item = String; type Error = io::Error; fn encode(&mut self, msg: String, buf: &mut BytesMut) -> io::Result<()> { Err(io::Error::new(io::ErrorKind::Other, "Not implemented")) } }
{ Err(io::Error::new(io::ErrorKind::Other, "Not implemented")) }
identifier_body
sensor_base.py
"""Support for the Philips Hue sensors as a platform.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohue import AiohueException, Unauthorized from aiohue.v1.sensors import TYPE_ZLL_PRESENCE import async_timeout from homeassistant.components.sensor i...
self._component_add_entities[platform] = async_add_entities if len(self._component_add_entities) < len(self._enabled_platforms): LOGGER.debug("Aborting start with %s, waiting for the rest", platform) return # We have all components available, start the updating. ...
random_line_split
sensor_base.py
"""Support for the Philips Hue sensors as a platform.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohue import AiohueException, Unauthorized from aiohue.v1.sensors import TYPE_ZLL_PRESENCE import async_timeout from homeassistant.components.sensor i...
base_name = api[item_id].name primary_sensor = primary_sensor_devices.get(_device_id(api[item_id])) if primary_sensor is not None: base_name = primary_sensor.name name = sensor_config["name_format"].format(base_name) current[uniqueid] = senso...
uniqueid = api[item_id].uniqueid if current.get(uniqueid, self.current_events.get(uniqueid)) is not None: continue sensor_type = api[item_id].type # Check for event generator devices event_config = EVENT_CONFIG_MAP.get(sensor_type) if event_c...
conditional_block
sensor_base.py
"""Support for the Philips Hue sensors as a platform.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohue import AiohueException, Unauthorized from aiohue.v1.sensors import TYPE_ZLL_PRESENCE import async_timeout from homeassistant.components.sensor i...
"""Representation of a Hue-brand, physical sensor.""" @property def extra_state_attributes(self): """Return the device state attributes.""" return {"battery_level": self.sensor.battery}
identifier_body
sensor_base.py
"""Support for the Philips Hue sensors as a platform.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohue import AiohueException, Unauthorized from aiohue.v1.sensors import TYPE_ZLL_PRESENCE import async_timeout from homeassistant.components.sensor i...
(self): """Return the state class of this entity, from STATE_CLASSES, if any.""" return SensorStateClass.MEASUREMENT async def async_added_to_hass(self): """When entity is added to hass.""" await super().async_added_to_hass() self.async_on_remove( self.bridge.sen...
state_class
identifier_name
pattern_constraints.py
# -*- coding: utf8 -*- # # electrode: numeric tools for Paul traps # # Copyright (C) 2011-2012 Robert Jordens <jordens@phys.ethz.ch> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, e...
def __init__(self, a, b): raise NotImplementedError
identifier_body
pattern_constraints.py
# -*- coding: utf8 -*- # # electrode: numeric tools for Paul traps # # Copyright (C) 2011-2012 Robert Jordens <jordens@phys.ethz.ch> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, e...
if self.min is not None: yield v >= float(self.min) if self.max is not None: yield v <= float(self.max) class PotentialObjective(SingleValueConstraint): """Constrain or optimize potential. Parameters ---------- x : array_like, shape (3,) ...
v = cvxopt.modeling.dot(d, variables) if self.offset is not None: yield v == float(self.offset)
random_line_split
pattern_constraints.py
# -*- coding: utf8 -*- # # electrode: numeric tools for Paul traps # # Copyright (C) 2011-2012 Robert Jordens <jordens@phys.ethz.ch> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, e...
(self, system, variables): for v in self.get(system, variables): if self.abs: v = abs(v) if self.norm == "one": yield cvxopt.modeling.sum(v) elif self.norm == "inf": yield cvxopt.modeling.max(v) else: ...
coef
identifier_name
pattern_constraints.py
# -*- coding: utf8 -*- # # electrode: numeric tools for Paul traps # # Copyright (C) 2011-2012 Robert Jordens <jordens@phys.ethz.ch> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, e...
if self.min is not None: for v in self.coef(system, variables): yield v >= float(self.min) class SymmetryConstaint(Constraint): def __init__(self, a, b): raise NotImplementedError
yield v <= float(self.max)
conditional_block
mssql_to_gcs.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
def query(self): """ Queries MSSQL and returns a cursor of results. :return: mssql cursor """ mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id) conn = mssql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor def ...
super().__init__(*args, **kwargs) self.mssql_conn_id = mssql_conn_id
identifier_body
mssql_to_gcs.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
sql='SELECT * FROM dbo.Customers;', bucket='mssql-export', filename='data/customers/export.json', schema_filename='schemas/export.json', mssql_conn_id='mssql_default', google_cloud_storage_conn_id='google_cloud_default', ...
within the given MSSQL Database and then upload it to the 'mssql-export' GCS bucket (along with a schema file). :: export_customers = MsSqlToGoogleCloudStorageOperator( task_id='export_customers',
random_line_split
mssql_to_gcs.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
(BaseSQLToGCSOperator): """Copy data from Microsoft SQL Server to Google Cloud Storage in JSON or CSV format. :param mssql_conn_id: Reference to a specific MSSQL hook. :type mssql_conn_id: str **Example**: The following operator will export data from the Customers table within the ...
MSSQLToGCSOperator
identifier_name
mssql_to_gcs.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
return value
return float(value)
conditional_block
materials.py
#!/usr/bin/python # -*- coding: utf8 -*- from bs4 import BeautifulSoup as Soup import urls import re import proxy from datetime import * import time from time import mktime import functions def
( config ): url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["school_id"]), str(config["team_element_id"]) ) cookies = {} # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTM...
materials
identifier_name
materials.py
#!/usr/bin/python
from bs4 import BeautifulSoup as Soup import urls import re import proxy from datetime import * import time from time import mktime import functions def materials ( config ): url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["school_id"]), str(config["team_element_id"]) ) ...
# -*- coding: utf8 -*-
random_line_split
materials.py
#!/usr/bin/python # -*- coding: utf8 -*- from bs4 import BeautifulSoup as Soup import urls import re import proxy from datetime import * import time from time import mktime import functions def materials ( config ): url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["schoo...
return { "status" : "ok", "materials" : materialsList }
rows.pop(0) titleProg = re.compile(ur"(?P<authors>.*): (?P<title>.*), (?P<publisher>.*)") for row in rows: elements = row.findAll("td") title = unicode(elements[0].text.replace("\n", "")) titleGroups = titleProg.match(title) materialsList.append({ "title_text" : title, "title" : titleGroups.gro...
conditional_block
materials.py
#!/usr/bin/python # -*- coding: utf8 -*- from bs4 import BeautifulSoup as Soup import urls import re import proxy from datetime import * import time from time import mktime import functions def materials ( config ):
return { "status" : False, "error" : "Data not found" } rows = soup.find("table", attrs={"id" : "m_Content_MaterialsStudents"}).findAll("tr") materialsList = [] if len(rows) > 1: rows.pop(0) titleProg = re.compile(ur"(?P<authors>.*): (?P<title>.*), (?P<publisher>.*)") for row in rows: elements ...
url = "https://www.lectio.dk/lectio/%s/MaterialOverview.aspx?holdelement_id=%s" % ( str(config["school_id"]), str(config["team_element_id"]) ) cookies = {} # Insert User-agent headers and the cookie information headers = { "User-Agent" : "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)...
identifier_body
no_0337_house_robber_iii.rs
// Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, lef...
al: 2, left: node(TreeNode::new(3)), right: None, }), right: None, }), right: None, }); assert_eq!(Solution::rob(root), 7); // 选了开头的4和末尾的3. } fn node(n: TreeNode) -> Option<Rc<RefCell<TreeNode>>> { ...
identifier_body
no_0337_house_robber_iii.rs
// Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, lef...
val: 2, left: node(TreeNode::new(3)), right: None, }), right: None, }), right: None, }); assert_eq!(Solution::rob(root), 7); // 选了开头的4和末尾的3. } fn node(n: TreeNode) -> Option<Rc<RefCell<TreeNode>>> ...
identifier_name
no_0337_house_robber_iii.rs
// Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, lef...
} }
Some(Rc::new(RefCell::new(n)))
random_line_split
no_0337_house_robber_iii.rs
// Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, lef...
let left_res = Self::rob_helper(r.left.clone()); let right_res = Self::rob_helper(r.right.clone()); ( // 没有选中间节点,左右子节点可以选(这里错了) // left_res.1 + right_res.1, // 没有选中间节点时,左右子节点可以选,也可以不选 left_res.0.max(left_res.1) + right_res.0.max(right_res.1), ...
r = root.as_ref().unwrap().borrow();
conditional_block
shl.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn
() { let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x << y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 4, 8, 12, 16, 20, 24, 28\ )".to_string()); } }
shl_test1
identifier_name
shl.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd]
#[test] fn shl_test1() { let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x << y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 4, 8, 12, 16, 20, 24, 28\ )".to_string()); } }
// #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16);
random_line_split
shl.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn shl_tes...
}
{ let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x << y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 4, 8, 12, 16, 20, 24, 28\ )".to_string()); }
identifier_body
timeGrid.ts
import { h } from "snabbdom/h" import { VNode } from "snabbdom/vnode" import * as Rx from "rxjs" export type Range = { min: number max: number } export type In = { selected: Rx.Observable<Range> bounds: Rx.Observable<Range>, unit: string, canvas: VNode, } function calc(e: MouseEvent, bounds: Range): numb...
}, resizers.concat(cursors)), input.canvas, h("div.resource-dividers", lines), h("div.timeline-grid-header", [h("div.resources-dividers-label-bar", labels)]), ]) return vnode }) return { selected: completedSelection.withLatestFrom(input.bounds, (range, bounds) => ...
mousedown: (e: MouseEvent) => activeDowns.next(percentage(e)), mousemove: (e: MouseEvent) => activeMoves.next(percentage(e)), mouseup: (e: MouseEvent) => activeUps.next(percentage(e)), },
random_line_split
timeGrid.ts
import { h } from "snabbdom/h" import { VNode } from "snabbdom/vnode" import * as Rx from "rxjs" export type Range = { min: number max: number } export type In = { selected: Rx.Observable<Range> bounds: Rx.Observable<Range>, unit: string, canvas: VNode, } function calc(e: MouseEvent, bounds: Range): numb...
function percReverse(bounds: Range, number: number): number { return bounds.min + (bounds.max - bounds.min) * number } export function horizontalSlider(input: In): { vnode: Rx.Observable<VNode>, selected: Rx.Observable<Range> } { let activeDowns = new Rx.Subject<number>() let activeMoves = new Rx.Subject<numbe...
{ return (number - bounds.min) / (bounds.max - bounds.min) }
identifier_body
timeGrid.ts
import { h } from "snabbdom/h" import { VNode } from "snabbdom/vnode" import * as Rx from "rxjs" export type Range = { min: number max: number } export type In = { selected: Rx.Observable<Range> bounds: Rx.Observable<Range>, unit: string, canvas: VNode, } function calc(e: MouseEvent, bounds: Range): numb...
(number: number): Range { return { min: number, max: number } } function tupleRange(a: number, b: number): Range { return { min: Math.min(a, b), max: Math.max(a, b) } } function perc(bounds: Range, number: number): number { return (number - bounds.min) / (bounds.max - bounds.min) } function percReverse(bounds: R...
singleRange
identifier_name
timeGrid.ts
import { h } from "snabbdom/h" import { VNode } from "snabbdom/vnode" import * as Rx from "rxjs" export type Range = { min: number max: number } export type In = { selected: Rx.Observable<Range> bounds: Rx.Observable<Range>, unit: string, canvas: VNode, } function calc(e: MouseEvent, bounds: Range): numb...
return r }
r.push(i) }
conditional_block
base.py
class Tool(object): '''Abstract base class for data analysis tools. Tools use the `Pandas DataFrame <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html>`_ data container. This is compatible with standard machine learning libries, such as `Scikit-Learn <http://scikit-learn....
def __call__(cls, *args, **kwargs): return super(_ToolMeta, cls).__call__(*args, **kwargs)
random_line_split
base.py
(cls, *args, **kwargs): return super(_ToolMeta, cls).__call__(*args, **kwargs) class Tool(object): '''Abstract base class for data analysis tools. Tools use the `Pandas DataFrame <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html>`_ data container. This is compatibl...
__call__
identifier_name
base.py
str name of the selected :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` feature_names: List[str] name of each selected :class:`Feature <tmlib.models.feature.Feature>` mapobject_ids: List[int], optional ID of each :class:`Mapobje...
filter_by(mapobject_type_id=mapobject_type.id).\ order_by(func.random()).\ limit(n).\ all() return [m.id for m in mapobjects] def partition_mapobjects(self, mapobject_type_name, n): '''Splits mapobjects into partitions of size `n`...
'''Selects a random subset of mapobjects. Parameters ---------- mapobject_type_name: str name of the selected :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` n: int number of mapobjects that should be selected at random Returns ...
identifier_body
base.py
name of the selected :class:`MapobjectType <tmlib.models.mapobject.MapobjectType>` feature_names: List[str] name of each selected :class:`Feature <tmlib.models.feature.Feature>` mapobject_ids: List[int], optional ID of each :class:`Mapobject <...
return df def calculate_extrema(self, mapobject_type_name, feature_name): '''Calculates minimum and maximum values of a given feature and mapobject type. Parameters ---------- mapobject_type_name: str name of the selected :class:`MapobjectT...
if count > 0: logger.warn('feature "%s" contains %d null values', name, count)
conditional_block
measureContext.ts
/** * @source: https://github.com/jnetterf/satie/ * * @license * (C) Josh Netterfield <joshua@nettek.ca> 2015. * Part of the Satie music engraver <https://github.com/jnetterf/satie>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public Li...
{ return { idx: measure.idx, uuid: measure.uuid, implicit: measure.implicit, attributes: null, nonControlling: measure.nonControlling, number: measure.number, x: x, parent: measure, version: measure.version }; }
identifier_body
measureContext.ts
/** * @source: https://github.com/jnetterf/satie/ * * @license * (C) Josh Netterfield <joshua@nettek.ca> 2015. * Part of the Satie music engraver <https://github.com/jnetterf/satie>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public Li...
*/ import IMeasure from "../document/measure"; import IAttributesSnapshot from "./attributesSnapshot"; interface IMeasureContext { /** * The index of a given bar, starting from 0. This may not be the same as number. */ idx: number; /** * The string that is displayed at the start of the...
random_line_split
measureContext.ts
/** * @source: https://github.com/jnetterf/satie/ * * @license * (C) Josh Netterfield <joshua@nettek.ca> 2015. * Part of the Satie music engraver <https://github.com/jnetterf/satie>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public Li...
(measure: IMeasure, x: number): IMeasureContext { return { idx: measure.idx, uuid: measure.uuid, implicit: measure.implicit, attributes: null, nonControlling: measure.nonControlling, number: measure.number, x: x, parent: measure, version: mea...
detachMeasureContext
identifier_name
nl2br.py
""" NL2BR Extension =============== A Python-Markdown extension to treat newlines as hard breaks; like GitHub-flavored Markdown does. Usage: >>> import markdown >>> print markdown.markdown('line 1\\nline 2', extensions=['nl2br']) <p>line 1<br /> line 2</p> Copyright 2011 [Brian Neal](http://deathofa...
(self, md, md_globals): br_tag = markdown.inlinepatterns.SubstituteTagPattern(BR_RE, 'br') md.inlinePatterns.add('nl', br_tag, '_end') def makeExtension(configs=None): return Nl2BrExtension(configs)
extendMarkdown
identifier_name
nl2br.py
""" NL2BR Extension =============== A Python-Markdown extension to treat newlines as hard breaks; like GitHub-flavored Markdown does. Usage: >>> import markdown >>> print markdown.markdown('line 1\\nline 2', extensions=['nl2br']) <p>line 1<br /> line 2</p> Copyright 2011 [Brian Neal](http://deathofa...
def makeExtension(configs=None): return Nl2BrExtension(configs)
class Nl2BrExtension(markdown.Extension): def extendMarkdown(self, md, md_globals): br_tag = markdown.inlinepatterns.SubstituteTagPattern(BR_RE, 'br') md.inlinePatterns.add('nl', br_tag, '_end')
random_line_split
nl2br.py
""" NL2BR Extension =============== A Python-Markdown extension to treat newlines as hard breaks; like GitHub-flavored Markdown does. Usage: >>> import markdown >>> print markdown.markdown('line 1\\nline 2', extensions=['nl2br']) <p>line 1<br /> line 2</p> Copyright 2011 [Brian Neal](http://deathofa...
def makeExtension(configs=None): return Nl2BrExtension(configs)
def extendMarkdown(self, md, md_globals): br_tag = markdown.inlinepatterns.SubstituteTagPattern(BR_RE, 'br') md.inlinePatterns.add('nl', br_tag, '_end')
identifier_body
script.py
= get_manifest(manifest, env=self.environment) except ValueError: manifest = get_manifest( # abspath() is important, or this will be considered # relative to Environment.directory. "file:%s" % os.path.abspath(manifest), ...
for bundle in self.environment: self.log.info('Checking asset: %s', bundle.output) if updater.needs_rebuild(bundle, self.environment): self.log.info(' needs update') needsupdate = True if needsupdate: sys.exit(-1) class CommandLineE...
self.log.debug('no updater configured, using TimestampUpdater') updater = TimestampUpdater()
conditional_block
script.py
n, b in self.environment._named_bundles.items() if n in bundle_names] else: # Includes unnamed bundles as well. bundles = [(None, b) for b in self.environment] # Determine common prefix for use with ``directory`` option. if directory: ...
WatchCommand.__init__(self, cmd_env) self.ns = argparse_ns
identifier_body
script.py
= get_manifest(manifest, env=self.environment) except ValueError: manifest = get_manifest( # abspath() is important, or this will be considered # relative to Environment.directory. "file:%s" % os.path.abspath(manifest), ...
class CleanCommand(Command): def __call__(self): """Delete generated assets. """ self.log.info('Cleaning generated assets...') for bundle in self.environment: if not bundle.output: continue file_path = bundle.resolve_output(self.environment) ...
random_line_split
script.py
= get_manifest(manifest, env=self.environment) except ValueError: manifest = get_manifest( # abspath() is important, or this will be considered # relative to Environment.directory. "file:%s" % os.path.abspath(manifest), ...
(Command): def __call__(self): """Check to see if assets need to be rebuilt. A non-zero exit status will be returned if any of the input files are newer (based on mtime) than their output file. This is intended to be used in pre-commit hooks. """ needsupdate = False...
CheckCommand
identifier_name
inprocess.rs
Factory; use crate::webgl_thread::{WebGLMainThread, WebGLThread, WebGLThreadInit}; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRRenderHan...
(webrender_gl: Rc<dyn gl::Gl>, channel: WebGLSender<WebGLMsg>) -> Self { OutputHandler { webrender_gl, webgl_channel: channel, lock_channel: webgl_channel().unwrap(), sync_objects: Default::default(), } } } /// Bridge between the WR frame outputs and ...
new
identifier_name
inprocess.rs
ContextFactory; use crate::webgl_thread::{WebGLMainThread, WebGLThread, WebGLThreadInit}; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRRe...
} } /// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait. type OutputHandlerData = Option<(u32, Size2D<i32>)>; struct OutputHandler { webrender_gl: Rc<dyn gl::Gl>, webgl_channel: WebGLSender<WebGLMsg>, // Used to avoid creating a new channel on each received WebRend...
self.sendable.unlock(id as usize);
random_line_split
inprocess.rs
Factory; use crate::webgl_thread::{WebGLMainThread, WebGLThread, WebGLThreadInit}; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRRenderHan...
(image_id, size, Some(gl_sync as gl::GLsync)) } } } impl webxr_api::WebGLExternalImageApi for SendableWebGLExternalImages { fn lock(&self, id: usize) -> Option<gl::GLsync> { let (_, _, gl_sync) = self.lock_and_get_current_texture(id); gl_sync } fn unlock(&self, id:...
{ if let Some(main_thread) = WebGLMainThread::on_current_thread() { // If we're on the same thread as WebGL, we can get the data directly let (image_id, size) = main_thread .thread_data .borrow_mut() .handle_lock_unsync(WebGLContextId(id as...
identifier_body
inprocess.rs
Factory; use crate::webgl_thread::{WebGLMainThread, WebGLThread, WebGLThreadInit}; use canvas_traits::webgl::webgl_channel; use canvas_traits::webgl::DOMToTextureCommand; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRRenderHan...
} fn clone_box(&self) -> Box<dyn webxr_api::WebGLExternalImageApi> { Box::new(Self::new(self.webgl_channel.clone())) } } /// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads. struct WebGLExternalImages { webrender_gl: Rc<dyn gl::Gl>, sendable: SendableWebGLExtern...
{ self.webgl_channel .send(WebGLMsg::Unlock(WebGLContextId(id as usize))) .unwrap() }
conditional_block
utils.ts
/// <reference path="../../client/typings/ycm.d.ts" /> import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocumentSyncKind, TextDocuments, TextDocument, Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult, TextDocumentPositionParams, CompletionItem, Comple...
(buffer: Buffer): string { return buffer.toString('utf8') } export function crossPlatformUri(uri: string) { return URI.parse(uri).fsPath } let isDebug = false export function loggerInit(debug: boolean) { isDebug = debug } export function logger(tag: string, ...args: any[]) { args.unshift(`[${tag}]`)...
crossPlatformBufferToString
identifier_name
utils.ts
/// <reference path="../../client/typings/ycm.d.ts" /> import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocumentSyncKind, TextDocuments, TextDocument, Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult, TextDocumentPositionParams, CompletionItem, Comple...
let extensions = new Map<string, string>() extensions.set('objective-c', 'objc') export function mapVSCodeLanguageIdToYcmFileType(languageId: string) { const type = extensions.get(languageId) if (type) return type else return languageId }
{ args.unshift(`[${tag}]`) /* tslint:disable:no-console */ if (isDebug) console.log.apply(console, args) /* tslint:enable:no-console */ }
identifier_body
utils.ts
/// <reference path="../../client/typings/ycm.d.ts" /> import { IPCMessageReader, IPCMessageWriter, createConnection, IConnection, TextDocumentSyncKind, TextDocuments, TextDocument, Diagnostic, DiagnosticSeverity, InitializeParams, InitializeResult, TextDocumentPositionParams, CompletionItem, Comple...
insertText: it.insertion_text, documentation: doc_str, sortText: _.padStart(index.toString(), len, '0') } as CompletionItem switch (it.kind || it.extra_menu_info) { case 'TYPE': case 'STRUCT': item.kind = CompletionItemKind.Inte...
} const item = { label: it.menu_text || it.insertion_text, detail: it.extra_menu_info,
random_line_split
remove_console.rs
use serde::Deserialize; use swc_atoms::JsWord; use swc_common::collections::AHashSet; use swc_common::DUMMY_SP; use swc_ecmascript::ast::*; use swc_ecmascript::utils::ident::IdentLike; use swc_ecmascript::utils::Id; use swc_ecmascript::visit::{noop_fold_type, Fold, FoldWith}; use crate::top_level_binding_collector::co...
{ #[serde(default)] pub exclude: Vec<JsWord>, } struct RemoveConsole { exclude: Vec<JsWord>, bindings: Vec<AHashSet<Id>>, in_function_params: bool, } impl RemoveConsole { fn is_global_console(&self, ident: &Ident) -> bool { &ident.sym == "console" && !self.bindings.iter().any(|x| x.co...
Options
identifier_name
remove_console.rs
use serde::Deserialize; use swc_atoms::JsWord; use swc_common::collections::AHashSet; use swc_common::DUMMY_SP; use swc_ecmascript::ast::*; use swc_ecmascript::utils::ident::IdentLike; use swc_ecmascript::utils::Id; use swc_ecmascript::visit::{noop_fold_type, Fold, FoldWith}; use crate::top_level_binding_collector::co...
fn fold_script(&mut self, script: Script) -> Script { self.bindings.push(collect_top_level_decls(&script)); let s = script.fold_with(self); self.bindings.pop().unwrap(); s } } pub fn remove_console(config: Config) -> impl Fold { let exclude = match config { Config:...
{ self.bindings.push(collect_top_level_decls(&module)); let m = module.fold_children_with(self); self.bindings.pop().unwrap(); m }
identifier_body
remove_console.rs
use serde::Deserialize; use swc_atoms::JsWord; use swc_common::collections::AHashSet; use swc_common::DUMMY_SP; use swc_ecmascript::ast::*; use swc_ecmascript::utils::ident::IdentLike; use swc_ecmascript::utils::Id; use swc_ecmascript::visit::{noop_fold_type, Fold, FoldWith}; use crate::top_level_binding_collector::co...
Expr::Ident(i) if self.is_global_console(i) => {} _ => return false, } // Check if the property is requested to be excluded. // Here we do an O(n) search on the list of excluded properties because the size // should be small. match &member_expr.prop { ...
// Only proceed if the object is the global `console` object. match &*member_expr.obj {
random_line_split
scratchcard.min.js
= [events]; } for(var i = 0; i < events.length; i++) { var eventName = events[i], splitName = eventName.split("*"); if(splitName.length <= 1){ if(!this.events[eventName]) { continue; } for(va...
} } } }; module.exports = EventEmitter; })(); },{}],2:[function(require,module,exports){ (function() { "use strict"; var EventEmitter = require("./events"); // Detect if we have a touch event var isTouch = !!('ontouchstart' in window); var eventName = (...
{ eventName = x; for(var o = 0; o < this.events[eventName].length; o++) { this.events[eventName][o].callback.apply(this.events[eventName][o].instance, args); } }
conditional_block
scratchcard.min.js
events = [events]; } for(var i = 0; i < events.length; i++) { var eventName = events[i], splitName = eventName.split("*"); if(splitName.length <= 1){ if(!this.events[eventName]) { continue; } ...
return self.canvas; }(this); } ScratchCard.prototype = Object.create(EventEmitter.prototype); /** * Draw the canvas and the buffer */ ScratchCard.prototype.draw = function() { var render = this.canvas, height = this.params.height, width ...
{ EventEmitter.call(this); this.$el = element; this.params = params; this.canvas = {}; this.complete = false; this.eventName = 'error'; this.requestId = 'error'; var init = function init(self) { Kiwapp.log('[ScratchCard@init] Cre...
identifier_body