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 |
|---|---|---|---|---|
context_singleton.py | # -*- coding: utf-8 -*-
'''
Copyright (c) 2013, LastSeal S.A.
Copyright (c) 2011-2012, Joaquin G. Duo
All rights reserved.
This code is distributed under BSD 3-clause License.
For details check the LICENSE file in the root of the project.
'''
class context_singleton(object):
'''
Singleton pattern decorator... | (self, class_):
self.class_ = class_
def __call__(self, context=None, *a, **ad):
if context == None:
msg = "You should always provide a context for class: %r" % self.class_.__class__.__name__
raise RuntimeError(msg)
if not context.has_config('singleton', self.class_):... | __init__ | identifier_name |
context_singleton.py | # -*- coding: utf-8 -*-
'''
Copyright (c) 2013, LastSeal S.A.
Copyright (c) 2011-2012, Joaquin G. Duo
All rights reserved.
This code is distributed under BSD 3-clause License.
For details check the LICENSE file in the root of the project.
'''
class context_singleton(object):
'''
Singleton pattern decorator... |
assert Example(ctx) == Example(ctx)
if __name__ == '__main__':
smokeTestModule()
| def __init__(self, context):
pass | identifier_body |
function.ts | import * as AST from "../../../ast";
import * as ASTTypes from "../../../ast/types";
import { nodeFromExpression } from "../../create";
import { SingleValuePort } from "../../ports/single";
import { Scope } from "../../scopes/scope";
import * as Types from "../../types";
import { checkType } from "../../types/check";
i... |
for (let i = 0; i < this.returns.length; i++) {
returns.push(
(this.inPorts[i + this.params.length].getData(new Types.Type()) as Values.Type).value);
}
return new Values.Type(new Types.Function(params, returns));
}
}
| {
params.push((this.inPorts[i].getData(new Types.Type()) as Values.Type).value);
} | conditional_block |
function.ts | import * as AST from "../../../ast";
import * as ASTTypes from "../../../ast/types";
import { nodeFromExpression } from "../../create";
import { SingleValuePort } from "../../ports/single";
import { Scope } from "../../scopes/scope";
import * as Types from "../../types";
import { checkType } from "../../types/check";
i... | this.params = [];
for (const expression of defintion.params) {
this.params.push(nodeFromExpression(expression, scope));
}
this.returns = [];
for (const expression of defintion.returns) {
this.params.push(nodeFromExpression(expression, scope));
}
this.addInPorts(this.params);
... | private returns: Node[];
constructor(defintion: ASTTypes.FunctionType, scope: Scope) {
super("FunctionType", defintion);
| random_line_split |
function.ts | import * as AST from "../../../ast";
import * as ASTTypes from "../../../ast/types";
import { nodeFromExpression } from "../../create";
import { SingleValuePort } from "../../ports/single";
import { Scope } from "../../scopes/scope";
import * as Types from "../../types";
import { checkType } from "../../types/check";
i... | extends Node {
private params: Node[];
private returns: Node[];
constructor(defintion: ASTTypes.FunctionType, scope: Scope) {
super("FunctionType", defintion);
this.params = [];
for (const expression of defintion.params) {
this.params.push(nodeFromExpression(expression, scope));
}
th... | FunctionType | identifier_name |
function.ts | import * as AST from "../../../ast";
import * as ASTTypes from "../../../ast/types";
import { nodeFromExpression } from "../../create";
import { SingleValuePort } from "../../ports/single";
import { Scope } from "../../scopes/scope";
import * as Types from "../../types";
import { checkType } from "../../types/check";
i... |
public fetchData(type: Types.ReadyType): Values.ReadyValue {
if (!checkType(new Types.Type(), type)) {
return new Values.ErrorValue("Incompartible type, not type");
}
const params: Types.Type[] = [];
const returns: Types.Type[] = [];
for (let i = 0; i < this.params.length; i++) {
p... | {
super("FunctionType", defintion);
this.params = [];
for (const expression of defintion.params) {
this.params.push(nodeFromExpression(expression, scope));
}
this.returns = [];
for (const expression of defintion.returns) {
this.params.push(nodeFromExpression(expression, scope));
... | identifier_body |
plocale.py | ############################################################################
# Copyright (C) 2005 by Reithinger GmbH
# mreithinger@web.de
# | #
# faces is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later versi... | # This file is part of faces. | random_line_split |
plocale.py | ############################################################################
# Copyright (C) 2005 by Reithinger GmbH
# mreithinger@web.de
#
# This file is part of faces.
#
# faces is free software; you can redistribute it and/or modify
# ... |
return locale.getpreferredencoding()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| return trans.charset() | conditional_block |
plocale.py | ############################################################################
# Copyright (C) 2005 by Reithinger GmbH
# mreithinger@web.de
#
# This file is part of faces.
#
# faces is free software; you can redistribute it and/or modify
# ... |
def get_gettext():
trans = _get_translation()
if trans: return trans.ugettext
return lambda msg: msg
def get_encoding():
trans = _get_translation()
if trans: return trans.charset()
return locale.getpreferredencoding()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwid... | try:
return gettext.translation("faces")
except:
try:
if sys.frozen:
path = os.path.dirname(sys.argv[0])
path = os.path.join(path, "resources", "faces", "locale")
else:
path = os.path.split(__file__)[0]
path = os... | identifier_body |
plocale.py | ############################################################################
# Copyright (C) 2005 by Reithinger GmbH
# mreithinger@web.de
#
# This file is part of faces.
#
# faces is free software; you can redistribute it and/or modify
# ... | ():
trans = _get_translation()
if trans: return trans.ugettext
return lambda msg: msg
def get_encoding():
trans = _get_translation()
if trans: return trans.charset()
return locale.getpreferredencoding()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| get_gettext | identifier_name |
processing-file_test.js | /*global require:true*/
(function( exports ){
"use strict";
var fs = require( 'fs' ); | var Pfile = require( '..' + fs.separator + '..' + fs.separator + 'lib' + fs.separator + 'processing-file' );
var bearSVG = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="62.905px">\n' +
'<path d="M11.068,34.558c-1.585-2.365-2.595-5.098-2.939-8.106c-0.344,0.092-0.666,0.161-1.033,0.161\n' +
'\tc-2.342,0-... | random_line_split | |
axe.config.js | /*jshint node: true*/
'use strict';
// Defaults derived from: https://github.com/dequelabs/axe-core
const defaults = {
rules: {
'area-alt': { 'enabled': true },
'audio-caption': { 'enabled': true },
'button-name': { 'enabled': true },
'document-title': { 'enabled': true },
'empty-heading': { 'ena... | 'meta-viewport': { 'enabled': true },
'meta-viewport-large': { 'enabled': true }
}
};
module.exports = {
getConfig: () => {
const skyPagesConfigUtil = require('../sky-pages/sky-pages.config');
const skyPagesConfig = skyPagesConfigUtil.getSkyPagesConfig();
let config = {};
// Merge rules f... | 'link-in-text-block': { 'enabled': true },
'marquee': { 'enabled': true }, | random_line_split |
axe.config.js | /*jshint node: true*/
'use strict';
// Defaults derived from: https://github.com/dequelabs/axe-core
const defaults = {
rules: {
'area-alt': { 'enabled': true },
'audio-caption': { 'enabled': true },
'button-name': { 'enabled': true },
'document-title': { 'enabled': true },
'empty-heading': { 'ena... |
return config;
}
};
| {
return defaults;
} | conditional_block |
tasks.py | entry in entries:
if os.path.isdir(tasks.get_container_dir(entry) + '/products'):
containers.append(entry)
return containers
@tasks.register_helper
def get_products(container_name):
products_dir = tasks.get_container_dir(container_name) + '/products'
if not os.path.isdir(products_dir)... |
print()
@tasks.register
def cd(doi):
"""
cd to directory of interest(doi)
a doi can be:
herbert - the container named "herbert"
sdox:dev - product "website" located in container "herbert"
:param doi:
:return:
"""
parts = doi.split(':')
if len(parts) == 2:
conta... | print(' ' + product_name) | conditional_block |
tasks.py | entry in entries:
if os.path.isdir(tasks.get_container_dir(entry) + '/products'):
containers.append(entry)
return containers
@tasks.register_helper
def get_products(container_name):
products_dir = tasks.get_container_dir(container_name) + '/products'
if not os.path.isdir(products_dir)... | (poi):
'''alias for "teleport"'''
tasks.teleport(poi)
@tasks.register
def install_container(container_name):
"""
Installs the container specified by container_name
:param container_name: string, name of the container
"""
container_dir = os.path.join(os.environ['APE_ROOT_DIR'], container_n... | zap | identifier_name |
tasks.py | entry in entries:
if os.path.isdir(tasks.get_container_dir(entry) + '/products'):
containers.append(entry)
return containers
@tasks.register_helper
def get_products(container_name):
products_dir = tasks.get_container_dir(container_name) + '/products'
if not os.path.isdir(products_dir)... |
@tasks.register_helper
def get_extra_pypath(container_name=None):
from ape.installtools import pypath
return pypath.get_extra_pypath()
@tasks.register_helper
def get_poi_tuple(poi=None):
"""
Takes the poi or None and returns the container_dir and the product name either of the passed poi
(<cont... | """
Installs the container specified by container_name
:param container_name: string, name of the container
"""
container_dir = os.path.join(os.environ['APE_ROOT_DIR'], container_name)
if os.path.exists(container_dir):
os.environ['CONTAINER_DIR'] = container_dir
else:
raise Cont... | identifier_body |
tasks.py | entry in entries:
if os.path.isdir(tasks.get_container_dir(entry) + '/products'):
containers.append(entry)
return containers
@tasks.register_helper
def get_products(container_name):
products_dir = tasks.get_container_dir(container_name) + '/products'
if not os.path.isdir(products_dir)... | # interpret poi as product name if already zapped into a product in order
# to enable simply switching products by doing ape zap prod.
container_name = os.environ.get('CONTAINER_NAME')
product_name = parts[0]
else:
print('unable to find poi: ', poi)
sys.exit(1)
i... |
parts = poi.split(':')
if len(parts) == 2:
container_name, product_name = parts
elif len(parts) == 1 and os.environ.get('CONTAINER_NAME'): | random_line_split |
management.py | 0.8.3.
# Buffer output until a client connects; then let the client
# drain the buffer.
# We keep the same read_buffer as before
self.read_buffer = deque([], maxlen=10)
self.preopen_buffer = deque([])
kwargs = dict(argv=argv, env=env, cwd=cwd)
if preexec_fn is no... |
class SingleTermManager(TermManagerBase):
"""All connections to the websocket share a common terminal."""
def __init__(self, **kwargs):
super(SingleTermManager, self).__init__(**kwargs)
self.terminal = None
def get_terminal(self, url_component=None):
if self.terminal is None:
... | await asyncio.gather(*futures) | conditional_block |
management.py | SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated. '''
if os.name == 'nt':
signals = [signal.SIGINT, signal.SIGTERM]
else:
signals = [signal.SIGHUP... | term = self.terminals[name]
term.kill(sig) # This should lead to an EOF | identifier_body | |
management.py | (object):
def __init__(self, argv, env=[], cwd=None):
self.clients = []
# If you start the process and then construct this object from it,
# output generated by the process prior to the object's creation
# is lost. Hence the change from 0.8.3.
# Buffer output until a clien... | PtyWithClients | identifier_name | |
management.py | 0.8.3.
# Buffer output until a client connects; then let the client
# drain the buffer.
# We keep the same read_buffer as before
self.read_buffer = deque([], maxlen=10)
self.preopen_buffer = deque([])
kwargs = dict(argv=argv, env=env, cwd=cwd)
if preexec_fn is n... | rows, cols = client.size
if rows is not None and rows < minrows:
minrows = rows
if cols is not None and cols < mincols:
mincols = cols
if minrows == 10001 or mincols == 10001:
return
rows, cols = self.ptyproc.getwinsize()
... | sized to the smallest client.
"""
minrows = mincols = 10001
for client in self.clients: | random_line_split |
datepicker.js | gapi.analytics.ready(function() {
var nDaysAgo = /(\d+)daysAgo/;
var dateFormat = /\d{4}\-\d{2}\-\d{2}/;
/**
* Convert a date acceptable to the Core Reporting API (e.g. `today`,
* `yesterday` or `NdaysAgo`) into the format YYYY-MM-DD. Dates
* already in that format are simply returned.
* @return {st... |
gapi.analytics.createComponent('Datepicker', {
/**
* Initialize the Datepicker instance and render it to the page.
* @return {Datepicker} The instance.
*/
execute: function() {
var options = this.get();
options['start-date'] = options['start-date'] || '7daysAgo';
options['e... | {
var date = new Date();
date.setDate(date.getDate() - numDays);
var month = String(date.getMonth() + 1);
month = month.length == 1 ? '0' + month: month;
var day = String(date.getDate());
day = day.length == 1 ? '0' + day: day;
return date.getFullYear() + '-' + month + '-' + day;
} | identifier_body |
datepicker.js | gapi.analytics.ready(function() {
var nDaysAgo = /(\d+)daysAgo/;
var dateFormat = /\d{4}\-\d{2}\-\d{2}/;
/**
* Convert a date acceptable to the Core Reporting API (e.g. `today`,
* `yesterday` or `NdaysAgo`) into the format YYYY-MM-DD. Dates
* already in that format are simply returned.
* @return {st... | (numDays) {
var date = new Date();
date.setDate(date.getDate() - numDays);
var month = String(date.getMonth() + 1);
month = month.length == 1 ? '0' + month: month;
var day = String(date.getDate());
day = day.length == 1 ? '0' + day: day;
return date.getFullYear() + '-' + month + '-' + day;
... | daysAgo | identifier_name |
datepicker.js | gapi.analytics.ready(function() {
var nDaysAgo = /(\d+)daysAgo/;
var dateFormat = /\d{4}\-\d{2}\-\d{2}/;
/**
* Convert a date acceptable to the Core Reporting API (e.g. `today`,
* `yesterday` or `NdaysAgo`) into the format YYYY-MM-DD. Dates
* already in that format are simply returned.
* @return {st... | * The html structure used to build the component. Developers can
* override this by passing it to the component constructor.
* The only requirement is that the structure contain two inputs, the
* first will be the start date and the second will be the end date.
*/
template:
'<div clas... | this.endDateInput.min = this.startDateInput.value;
},
/** | random_line_split |
command.py | # -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from django.db import transaction
from django.utils.translation import ugettext as _
from django.conf import settings
from orgs.mixins.api import RootOrgViewMixin
from common.permissions import IsValidUs... | args=(instance.id,), kwargs={"cols": cols, "rows": rows},
task_id=str(instance.id)
)) | transaction.on_commit(lambda: run_command_execution.apply_async( | random_line_split |
command.py | # -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from django.db import transaction
from django.utils.translation import ugettext as _
from django.conf import settings
from orgs.mixins.api import RootOrgViewMixin
from common.permissions import IsValidUs... | (self, request):
if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user:
return self.permission_denied(request, "Command execution disabled")
return super().check_permissions(request)
def perform_create(self, serializer):
self.check_hosts(serializer)
... | check_permissions | identifier_name |
command.py | # -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from django.db import transaction
from django.utils.translation import ugettext as _
from django.conf import settings
from orgs.mixins.api import RootOrgViewMixin
from common.permissions import IsValidUs... |
return super().check_permissions(request)
def perform_create(self, serializer):
self.check_hosts(serializer)
instance = serializer.save()
instance.user = self.request.user
instance.save()
cols = self.request.query_params.get("cols", '80')
rows = self.request... | return self.permission_denied(request, "Command execution disabled") | conditional_block |
command.py | # -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from django.db import transaction
from django.utils.translation import ugettext as _
from django.conf import settings
from orgs.mixins.api import RootOrgViewMixin
from common.permissions import IsValidUs... | raise ValidationError({"hosts": msg})
def check_permissions(self, request):
if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user:
return self.permission_denied(request, "Command execution disabled")
return super().check_permissions(request)
def per... | serializer_class = CommandExecutionSerializer
permission_classes = (IsValidUser,)
def get_queryset(self):
return CommandExecution.objects.filter(
user_id=str(self.request.user.id)
)
def check_hosts(self, serializer):
data = serializer.validated_data
assets = dat... | identifier_body |
blockchain.js | /* globals Promise:true */
var _ = require('lodash')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var LRU = require('lru-cache')
var Promise = require('bluebird')
var Snapshot = require('./snapshot')
var errors = require('../errors')
var util = require('../util')
/**
* @... |
self._isSyncing = false
self.on('syncStart', function () { self._isSyncing = true })
self.on('syncStop', function () { self._isSyncing = false })
}
inherits(Blockchain, EventEmitter)
Blockchain.prototype._syncStart = function () {
if (!this.isSyncing()) this.emit('syncStart')
}
Blockchain.prototype._syncSto... | self.latest = {hash: util.zfill('', 64), height: -1}
self._txCache = LRU({max: opts.txCacheSize, allowSlate: true}) | random_line_split |
blockchain.js | /* globals Promise:true */
var _ = require('lodash')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var LRU = require('lru-cache')
var Promise = require('bluebird')
var Snapshot = require('./snapshot')
var errors = require('../errors')
var util = require('../util')
/**
* @... |
inherits(Blockchain, EventEmitter)
Blockchain.prototype._syncStart = function () {
if (!this.isSyncing()) this.emit('syncStart')
}
Blockchain.prototype._syncStop = function () {
if (this.isSyncing()) this.emit('syncStop')
}
/**
* @param {errors.Connector} err
* @throws {errors.Connector}
*/
Blockchain.proto... | {
var self = this
EventEmitter.call(self)
opts = _.extend({
networkName: 'livenet',
txCacheSize: 100
}, opts)
self.connector = connector
self.networkName = opts.networkName
self.latest = {hash: util.zfill('', 64), height: -1}
self._txCache = LRU({max: opts.txCacheSize, allowSlate: true})
se... | identifier_body |
blockchain.js | /* globals Promise:true */
var _ = require('lodash')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var LRU = require('lru-cache')
var Promise = require('bluebird')
var Snapshot = require('./snapshot')
var errors = require('../errors')
var util = require('../util')
/**
* @... | (connector, opts) {
var self = this
EventEmitter.call(self)
opts = _.extend({
networkName: 'livenet',
txCacheSize: 100
}, opts)
self.connector = connector
self.networkName = opts.networkName
self.latest = {hash: util.zfill('', 64), height: -1}
self._txCache = LRU({max: opts.txCacheSize, allow... | Blockchain | identifier_name |
shortest_distance_between_words_1.py | """
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", return 1
"""
c... | (self, lst, word1, word2):
m = len(lst)
a , b = -1, -1
for i in range(len(lst)):
if lst[i] == word1:
a = i
if lst[i] == word2:
b = i
if a != -1 and b != -1:
m = min(m, abs(a-b))
return m
print Solutio... | shortest | identifier_name |
shortest_distance_between_words_1.py | """
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
| Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", return 1
"""
class Solution():
def __init__(self):
pass
def shortest(self, lst, word1, word2):
m = len(lst)
a , b = -1, -1
for i in range(len(lst)):
if lst[i] == word1:
... | random_line_split | |
shortest_distance_between_words_1.py | """
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", return 1
"""
c... |
if a != -1 and b != -1:
m = min(m, abs(a-b))
return m
print Solution().shortest(["practice", "makes", "perfect", "coding", "makes"], "practice", "perfect") | b = i | conditional_block |
shortest_distance_between_words_1.py | """
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = "coding", word2 = "practice", return 3. Given word1 = "makes", word2 = "coding", return 1
"""
c... |
print Solution().shortest(["practice", "makes", "perfect", "coding", "makes"], "practice", "perfect") | m = len(lst)
a , b = -1, -1
for i in range(len(lst)):
if lst[i] == word1:
a = i
if lst[i] == word2:
b = i
if a != -1 and b != -1:
m = min(m, abs(a-b))
return m | identifier_body |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... | }
/// Thread-safe logic to create thread-scoped `Authenticator` instances.
///
/// This allows implementations to initiate and share global state once for the entire process
/// while also allowing the use of thread-scoped objects where needed.
#[derive(Clone)]
pub struct AuthenticatorFactory {
factory: Arc<dyn Au... | random_line_split | |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... | (config: &Config) -> Result<AuthenticatorFactory> {
let factory: Arc<dyn AuthenticationProxyFactory> = match config.authenticator.backend {
#[cfg(debug_assertions)]
AuthenticatorBackend::AllowAll => Arc::new(self::allow_all::AllowAll {}),
AuthenticatorBackend::OAuth2Proxy(ref... | factory | identifier_name |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... |
// Process post-authentication rules.
let postauth = self
.rules
.eval_postauth(context, &result.authentication_context);
match postauth {
RuleAction::Allow => {
result.audit_reason = AuditReason::PostAuthAllowed;
result.statu... | {
return Ok(result);
} | conditional_block |
mod.rs | use std::sync::Arc;
use actix_web::HttpRequest;
use anyhow::Result;
use crate::config::AuthenticatorBackend;
use crate::config::Config;
use crate::engine::RulesEngine;
use crate::models::AuditReason;
use crate::models::AuthenticationResult;
use crate::models::AuthenticationStatus;
use crate::models::RequestContext;
u... |
/// Instantiate an authenticator from the given authentication proxy.
#[cfg(test)]
pub fn from<A>(authenticator: A) -> Authenticator
where
A: AuthenticationProxy + 'static,
{
let headers = IdentityHeaders::default();
let rules = RulesEngine::builder().build().unwrap();
... | {
let factory: Arc<dyn AuthenticationProxyFactory> = match config.authenticator.backend {
#[cfg(debug_assertions)]
AuthenticatorBackend::AllowAll => Arc::new(self::allow_all::AllowAll {}),
AuthenticatorBackend::OAuth2Proxy(ref oauth2_proxy) => Arc::new(
self::... | identifier_body |
mainThreadQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (instance: number, options: IPickOptions<TransferQuickPickItems>, token: CancellationToken): Promise<number | number[] | undefined> {
const contents = new Promise<TransferQuickPickItems[]>((resolve, reject) => {
this._items[instance] = { resolve, reject };
});
options = {
...options,
onDidFocus: el => {... | $show | identifier_name |
mainThreadQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
$setItems(instance: number, items: TransferQuickPickItems[]): Promise<void> {
if (this._items[instance]) {
this._items[instance].resolve(items);
delete this._items[instance];
}
return Promise.resolve();
}
$setError(instance: number, error: Error): Promise<void> {
if (this._items[instance]) {
t... | {
return this._quickInputService.pick(contents, options, token).then(item => {
if (item) {
return item.handle;
}
return undefined;
});
} | conditional_block |
mainThreadQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | private readonly _items: Record<number, {
resolve(items: TransferQuickPickItems[]): void;
reject(error: Error): void;
}> = {};
constructor(
extHostContext: IExtHostContext,
@IQuickInputService quickInputService: IQuickInputService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostQuickOpen)... | private readonly _quickInputService: IQuickInputService; | random_line_split |
mainThreadQuickOpen.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
// ---- QuickInput
private sessions = new Map<number, QuickInputSession>();
$createOrUpdate(params: TransferQuickInput): Promise<void> {
const sessionId = params.id;
let session = this.sessions.get(sessionId);
if (!session) {
if (params.type === 'quickPick') {
const input = this._quickInputService.c... | {
const inputOptions: IInputOptions = Object.create(null);
if (options) {
inputOptions.password = options.password;
inputOptions.placeHolder = options.placeHolder;
inputOptions.valueSelection = options.valueSelection;
inputOptions.prompt = options.prompt;
inputOptions.value = options.value;
input... | identifier_body |
Drag.js | po.drag = function() {
var drag = {},
map,
container,
dragging;
function mousedown(e) {
if (e.shiftKey) return;
dragging = {
x: e.clientX,
y: e.clientY
};
map.focusableParent().focus();
e.preventDefault();
document.body.style.setProperty("cursor", "move", null)... |
drag.map = function(x) {
if (!arguments.length) return map;
if (map) {
container.removeEventListener("mousedown", mousedown, false);
container = null;
}
if (map = x) {
container = map.container();
container.addEventListener("mousedown", mousedown, false);
}
return dra... | {
if (!dragging) return;
mousemove(e);
dragging = null;
document.body.style.removeProperty("cursor");
} | identifier_body |
Drag.js | po.drag = function() {
var drag = {},
map,
container,
dragging;
| y: e.clientY
};
map.focusableParent().focus();
e.preventDefault();
document.body.style.setProperty("cursor", "move", null);
}
function mousemove(e) {
if (!dragging) return;
map.panBy({x: e.clientX - dragging.x, y: e.clientY - dragging.y});
dragging.x = e.clientX;
dragging.y = ... | function mousedown(e) {
if (e.shiftKey) return;
dragging = {
x: e.clientX, | random_line_split |
Drag.js | po.drag = function() {
var drag = {},
map,
container,
dragging;
function | (e) {
if (e.shiftKey) return;
dragging = {
x: e.clientX,
y: e.clientY
};
map.focusableParent().focus();
e.preventDefault();
document.body.style.setProperty("cursor", "move", null);
}
function mousemove(e) {
if (!dragging) return;
map.panBy({x: e.clientX - dragging.x, y: ... | mousedown | identifier_name |
breakpointValidationFor.ts | /// <reference path='fourslash.ts' />
// @BaselineFile: bpSpan_for.baseline
// @Filename: bpSpan_for.ts
////for (var i = 0; i < 10; i++) {
//// WScript.Echo("i: " + i);
////}
////for (i = 0; i < 10; i++)
////{
//// WScript.Echo("i: " + i);
////}
////for (var j = 0; j < 10; ) {
//// j++;
//// i... | //// j++;
////}
////for (var k = 0;; k++) {
////}
////for (k = 0;; k++)
////{
////}
////for (; k < 10; k++) {
////}
////for (;;) {
//// i++;
////}
////for (;;)
////{
//// i++;
////}
////for (i = 0, j = 20; j < 20, i < 20; j++) {
////}
verify.baselineCurrentFileBreakpointLocations(); | ////}
////for (j = 0; j < 10;)
////{
| random_line_split |
shared.module.ts | import { NgModule, } from '@angular/core';
import { CommonModule, } from '@angular/common';
import {
CovalentLayoutModule, CovalentStepsModule, CovalentCommonModule,
CovalentMessageModule /*, any other modules */
} from '@covalent/core';
import {
MatListModule,
MdButtonModule,
MdCardModule,
Md... | {
}
| SharedModule | identifier_name |
shared.module.ts | import { NgModule, } from '@angular/core';
import { CommonModule, } from '@angular/common';
import {
CovalentLayoutModule, CovalentStepsModule, CovalentCommonModule,
CovalentMessageModule /*, any other modules */
} from '@covalent/core';
import {
MatListModule,
MdButtonModule,
MdCardModule,
Md... | ],
exports: [
ANGULAR_MODULES,
MATERIAL_MODULES,
COVALENT_MODULES,
FLEX_LAYOUT_MODULES,
OTHER_MODULES,
]
})
export class SharedModule {
} | ],
declarations: [
| random_line_split |
shipping-region.component.ts | import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Page } from '../../models/page';
import { ActivatedRoute, Router } from '@angular/router';
import { MatxPromptController } from 'angular-material-extended';
import { map, switchMap } from 'rxjs/operators';
import { PageEvent ... | templateUrl: './shipping-region.component.html',
styleUrls: ['./shipping-region.component.scss']
})
export class ShippingRegionComponent implements OnInit {
columns = ['shippingRegion', 'actions'];
dataSource$: Observable<ShippingRegion[]>;
params: any = {};
page: Page<ShippingRegion> = {
size: 20,
... |
@Component({
selector: 'app-shipping-region', | random_line_split |
shipping-region.component.ts | import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Page } from '../../models/page';
import { ActivatedRoute, Router } from '@angular/router';
import { MatxPromptController } from 'angular-material-extended';
import { map, switchMap } from 'rxjs/operators';
import { PageEvent ... |
handlePageChange(event: PageEvent) {
this.navigate({...this.params, page: event.pageIndex + 1, limit: event.pageSize});
}
@debounceFn(500)
search(search: string) {
this.navigate({search: search || null});
}
refresh() {
this.router.navigate([], {
relativeTo: this.route,
queryParam... | {
this.router.navigate([], {relativeTo: this.route, queryParams: params});
} | identifier_body |
shipping-region.component.ts | import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { Page } from '../../models/page';
import { ActivatedRoute, Router } from '@angular/router';
import { MatxPromptController } from 'angular-material-extended';
import { map, switchMap } from 'rxjs/operators';
import { PageEvent ... | () {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {_refresh: new Date().getTime()},
skipLocationChange: true
});
}
deleteById(id: any) {
this.promptCtrl.prompt({
message: 'Are you sure you want to delete this item?',
actions: ['No', {
text: 'Yes'... | refresh | identifier_name |
Three.js | /* global describe, it */
var assert = require('assert');
var jsdom = require('mocha-jsdom');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var stubContext = require('react-stub-context');
var Three = require('../src/Three');
describe('Three', function () {
jsdom();
var levels, con... | }); | });
}); | random_line_split |
filter.ts | import { AsyncIterableX } from '../../asynciterable/asynciterablex';
import { FilterAsyncIterable } from '../../asynciterable/operators/filter';
/**
* @ignore
*/
export function filterProto<T, S extends T>(
this: AsyncIterableX<T>,
predicate: (value: T, index: number, signal?: AbortSignal) => value is S,
thisA... | thisArg?: any
): AsyncIterableX<T> {
return new FilterAsyncIterable<T>(this, predicate, thisArg);
}
AsyncIterableX.prototype.filter = filterProto;
declare module '../../asynciterable/asynciterablex' {
interface AsyncIterableX<T> {
filter: typeof filterProto;
}
} | random_line_split | |
filter.ts | import { AsyncIterableX } from '../../asynciterable/asynciterablex';
import { FilterAsyncIterable } from '../../asynciterable/operators/filter';
/**
* @ignore
*/
export function filterProto<T, S extends T>(
this: AsyncIterableX<T>,
predicate: (value: T, index: number, signal?: AbortSignal) => value is S,
thisA... | <T>(
this: AsyncIterableX<T>,
predicate: (value: T, index: number, signal?: AbortSignal) => boolean | Promise<boolean>,
thisArg?: any
): AsyncIterableX<T> {
return new FilterAsyncIterable<T>(this, predicate, thisArg);
}
AsyncIterableX.prototype.filter = filterProto;
declare module '../../asynciterable/asyncit... | filterProto | identifier_name |
filter.ts | import { AsyncIterableX } from '../../asynciterable/asynciterablex';
import { FilterAsyncIterable } from '../../asynciterable/operators/filter';
/**
* @ignore
*/
export function filterProto<T, S extends T>(
this: AsyncIterableX<T>,
predicate: (value: T, index: number, signal?: AbortSignal) => value is S,
thisA... |
AsyncIterableX.prototype.filter = filterProto;
declare module '../../asynciterable/asynciterablex' {
interface AsyncIterableX<T> {
filter: typeof filterProto;
}
}
| {
return new FilterAsyncIterable<T>(this, predicate, thisArg);
} | identifier_body |
ProductionStep.py | """ Class defining a production step """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import json
from DIRAC import S_OK, S_ERROR
class ProductionStep(object):
"""Define the Production Step object"""
def __init__(self, **k... | else:
return S_ERROR("Invalid Parent Step")
prodStepDict["description"] = self.Description
prodStepDict["longDescription"] = self.LongDescription
prodStepDict["stepType"] = self.Type
prodStepDict["plugin"] = self.Plugin
prodStepDict["agentType"] = sel... | prodStepDict["parentStep"].append(parentStep.Name)
elif isinstance(self.ParentStep, ProductionStep):
if not self.ParentStep.Name:
return S_ERROR("Parent Step does not exist")
prodStepDict["parentStep"] = [self.ParentStep.Name] | random_line_split |
ProductionStep.py | """ Class defining a production step """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import json
from DIRAC import S_OK, S_ERROR
class ProductionStep(object):
"""Define the Production Step object"""
def __init__(self, **k... |
prodStepDict["parentStep"].append(parentStep.Name)
elif isinstance(self.ParentStep, ProductionStep):
if not self.ParentStep.Name:
return S_ERROR("Parent Step does not exist")
prodStepDict["parentStep"] = [self.ParentStep.Name]
... | return S_ERROR("Parent Step does not exist") | conditional_block |
ProductionStep.py | """ Class defining a production step """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import json
from DIRAC import S_OK, S_ERROR
class ProductionStep(object):
"""Define the Production Step object"""
def __init__(self, **k... | prodStepDict["longDescription"] = self.LongDescription
prodStepDict["stepType"] = self.Type
prodStepDict["plugin"] = self.Plugin
prodStepDict["agentType"] = self.AgentType
prodStepDict["fileMask"] = self.FileMask
# Optional fields
prodStepDict["inputquery"] = json... | """It returns the Step description as a dictionary"""
prodStepDict = {}
prodStepDict["name"] = self.Name
prodStepDict["parentStep"] = []
# check the ParentStep format
if self.ParentStep:
if isinstance(self.ParentStep, list):
prodStepDict["parentStep"] ... | identifier_body |
ProductionStep.py | """ Class defining a production step """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import json
from DIRAC import S_OK, S_ERROR
class | (object):
"""Define the Production Step object"""
def __init__(self, **kwargs):
"""Simple constructor"""
# Default values for transformation step parameters
self.Name = ""
self.Description = "description"
self.LongDescription = "longDescription"
self.Type = "MCS... | ProductionStep | identifier_name |
state.py | """Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)
from... | (states: Iterable[State],
utc_point_in_time: dt.datetime) -> List[State]:
"""Return list of states that have been changed since utc_point_in_time."""
return [state for state in states
if state.last_updated >= utc_point_in_time]
@bind_hass
def reproduce_state(hass: HomeAssista... | get_changed_since | identifier_name |
state.py | """Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)
from... | blocking=blocking,
context=context)
if to_call:
# run all domains in parallel
await asyncio.gather(*[
worker(domain, data)
for domain, data in to_call.items()
])
@bind_hass
async def async_reproduce_state_legacy(
hass: HomeA... | """Reproduce a list of states on multiple domains."""
if isinstance(states, State):
states = [states]
to_call = defaultdict(list) # type: Dict[str, List[State]]
for state in states:
to_call[state.domain].append(state)
async def worker(domain: str, data: List[State]) -> None:
... | identifier_body |
state.py | """Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)
from... |
if domain_tasks:
await asyncio.wait(domain_tasks, loop=hass.loop)
def state_as_number(state: State) -> float:
"""
Try to coerce our state to a number.
Raises ValueError if this is not possible.
"""
from homeassistant.components.climate import (
STATE_HEAT, STATE_COOL, STATE_... | data = json.loads(service_data)
data[ATTR_ENTITY_ID] = entity_ids
domain_tasks.append(
hass.services.async_call(service_domain, service, data, blocking,
context)
) | conditional_block |
state.py | """Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)
from... | SERVICE_SET_COVER_TILT_POSITION: [ATTR_TILT_POSITION]
}
# Update this dict when new services are added to HA.
# Each item is a service with a corresponding state.
SERVICE_TO_STATE = {
SERVICE_TURN_ON: STATE_ON,
SERVICE_TURN_OFF: STATE_OFF,
SERVICE_ALARM_ARM_AWAY: STATE_ALARM_ARMED_AWAY,
SERVICE_ALA... | SERVICE_SET_COVER_POSITION: [ATTR_POSITION], | random_line_split |
LegalHoldDot.test.tsx | /*
* Wire
* Copyright (C) 2021 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This progr... | }
getPendingIcon = () => this.get('svg[data-uie-name="legal-hold-dot-pending-icon"]');
}
describe('LegalHoldDot', () => {
it('shows a pending icon', () => {
const legalHoldModal = {
showRequestModal: () => Promise.resolve(),
showUsers: () => Promise.resolve(),
} as LegalHoldModalViewModel;
... | import {LegalHoldModalViewModel} from '../view_model/content/LegalHoldModalViewModel';
class LegalHoldDotPage extends TestPage<LegalHoldDotProps> {
constructor(props?: LegalHoldDotProps) {
super(LegalHoldDot, props); | random_line_split |
LegalHoldDot.test.tsx | /*
* Wire
* Copyright (C) 2021 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This progr... | extends TestPage<LegalHoldDotProps> {
constructor(props?: LegalHoldDotProps) {
super(LegalHoldDot, props);
}
getPendingIcon = () => this.get('svg[data-uie-name="legal-hold-dot-pending-icon"]');
}
describe('LegalHoldDot', () => {
it('shows a pending icon', () => {
const legalHoldModal = {
showRe... | LegalHoldDotPage | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e... |
return False
class Author(models.Model):
"""
Model representing an author.
"""
class Meta:
permissions = (("can_edit_author", "Edit author"),)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=... | return True | conditional_block |
models.py | from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e... | return False
class Author(models.Model):
"""
Model representing an author.
"""
class Meta:
permissions = (("can_edit_author", "Edit author"),)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=T... | def is_overdue(self):
if self.due_back and date.today() > self.due_back:
return True | random_line_split |
models.py | from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e... |
"""
Model representing a specific copy of a book (i.e. that can be borrowed from the library).
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library")
book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)... | permissions = (("can_mark_returned", "Set book as returned"),)
ordering = ["due_back"] | identifier_body |
models.py | from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e... | (self):
if self.due_back and date.today() > self.due_back:
return True
return False
class Author(models.Model):
"""
Model representing an author.
"""
class Meta:
permissions = (("can_edit_author", "Edit author"),)
first_name = models.CharField(max_length=100)
... | is_overdue | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::error::{Fallible};
use ... |
pub fn Append_(&mut self, name: DOMString, value: DOMString) {
self.data.insert(name, StringData(value));
}
}
impl Reflectable for FormData {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
fn mut_reflector<'a>(&'a mut self) -> &'a mut Reflector {
&mut se... | {
let blob = BlobData {
blob: value.clone(),
name: filename.unwrap_or(~"default")
};
self.data.insert(name.clone(), blob);
} | identifier_body |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::error::{Fallible};
use ... | (window: &JS<Window>, form: Option<JS<HTMLFormElement>>)
-> Fallible<JS<FormData>> {
Ok(FormData::new(form, window))
}
pub fn Append(&mut self, name: DOMString, value: &JS<Blob>, filename: Option<DOMString>) {
let blob = BlobData {
blob: value.clone(),
... | Constructor | identifier_name |
formdata.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::bindings::error::{Fallible};
use ... | use dom::blob::Blob;
use dom::htmlformelement::HTMLFormElement;
use dom::window::Window;
use servo_util::str::DOMString;
use collections::hashmap::HashMap;
#[deriving(Encodable)]
pub enum FormDatum {
StringData(DOMString),
BlobData { blob: JS<Blob>, name: DOMString }
}
#[deriving(Encodable)]
pub struct FormD... | random_line_split | |
test_modelfield.py | from django import forms
from example.models import OneUrlModel, ManyUrlsModel
def test_one_url(db):
class F(forms.ModelForm):
class Meta:
model = OneUrlModel
fields = '__all__'
form = F({'url': 'ya.RU'})
instance = form.save()
assert instance.url == 'http://ya.ru'
... | assert instance.urls == [
'http://xx.com',
'http://ya.ru',
'http://zzz.ff',
]
form = F(instance=instance)
assert bool(form.errors) == False
def test_model(db):
instance = ManyUrlsModel.objects.create(
urls=['http://ya.ru', 'http://xx.com'],
)
assert ManyUr... | random_line_split | |
test_modelfield.py | from django import forms
from example.models import OneUrlModel, ManyUrlsModel
def test_one_url(db):
class F(forms.ModelForm):
class Meta:
model = OneUrlModel
fields = '__all__'
form = F({'url': 'ya.RU'})
instance = form.save()
assert instance.url == 'http://ya.ru'
... | :
model = ManyUrlsModel
fields = '__all__'
form = F({'urls': 'ya.RU, xx.com '
'httP://zzz.ff'})
assert form.is_valid()
instance = form.save()
assert instance.urls == [
'http://xx.com',
'http://ya.ru',
'http://zzz.ff',
]
f... | Meta | identifier_name |
test_modelfield.py | from django import forms
from example.models import OneUrlModel, ManyUrlsModel
def test_one_url(db):
class F(forms.ModelForm):
class Meta:
model = OneUrlModel
fields = '__all__'
form = F({'url': 'ya.RU'})
instance = form.save()
assert instance.url == 'http://ya.ru'
... |
def test_model(db):
instance = ManyUrlsModel.objects.create(
urls=['http://ya.ru', 'http://xx.com'],
)
assert ManyUrlsModel.objects.get(id=instance.id).urls == ['http://ya.ru', 'http://xx.com']
instance = ManyUrlsModel.objects.create(
urls='http://ya.ru',
)
assert ManyUrlsM... | class F(forms.ModelForm):
class Meta:
model = ManyUrlsModel
fields = '__all__'
form = F({'urls': 'ya.RU, xx.com '
'httP://zzz.ff'})
assert form.is_valid()
instance = form.save()
assert instance.urls == [
'http://xx.com',
'http://y... | identifier_body |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | window.set_close_polling(true);
window.set_refresh_polling(true);
window.set_focus_polling(true);
window.set_iconify_polling(true);
window.set_framebuffer_size_polling(true);
window.set_key_polling(true);
window.set_char_polling(true);
window.set_char_mods_polling(true);
window.set_m... | {
let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
glfw.window_hint(glfw::WindowHint::Resizable(true));
let (mut window, events) = glfw
.create_window(
800,
600,
"Hello, I am a window.",
glfw::WindowMode::Windowed,
)
.expect(... | identifier_body |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | let (window_width, window_height) = window.get_size();
window.set_size(window_width + 1, window_height);
window.set_size(window_width, window_height);
}
_ => {}
}
}
glfw::WindowEvent::FileDrop(paths) ... | // Resize should cause the window to "refresh" | random_line_split |
events.rs | // Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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... | (window: &mut glfw::Window, (time, event): (f64, glfw::WindowEvent)) {
match event {
glfw::WindowEvent::Pos(x, y) => {
window.set_title(&format!("Time: {:?}, Window pos: ({:?}, {:?})", time, x, y))
}
glfw::WindowEvent::Size(w, h) => window.set_title(&format!(
"Time: {... | handle_window_event | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Authors: Stéphane Bidoul & Olivier Laurent
# Copyright (c) 2012 Acsone SA/NV (http://www.acsone.eu)
# All Rights Reserved
#
# WARNING: This program as such is intended to be used by professional
# programmers who ... | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
from . import hr_utilization_print | # along with this program; if not, write to the Free Software | random_line_split |
structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.js | [ "FloatAxial", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#addb3b8ac33094e21bd68f06c05af9ecf", null ],
[ "FloatAxial", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a04a78a140b41b1220373d94fb91dab28", null ],
[ "ToFloatCubic", "structca_1_1axoninteractive... | var structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial =
[ | random_line_split | |
issue-23302.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
issue-23302.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | enum Y {
A = Y::B as isize, //~ ERROR E0265
B,
}
fn main() { } |
// Since `Y::B` here defaults to `Y::A+1`, this is also a
// recursive definition. | random_line_split |
issue-23302.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { } | identifier_body | |
softmax_op_test.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 a... |
else:
return softmax
def _testSoftmax(self, np_features, log=False, use_gpu=False):
np_softmax = self._npSoftmax(np_features, log=log)
with self.test_session(use_gpu=use_gpu):
if log:
tf_softmax = tf.nn.log_softmax(np_features)
else:
tf_softmax = tf.nn.softmax(np_featur... | return np.log(softmax) | conditional_block |
softmax_op_test.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 a... | tf.nn.log_softmax([0., 1., 2., 3.])
def _testOverflow(self, use_gpu=False):
if use_gpu:
type = np.float32
else:
type = np.float64
max = np.finfo(type).max
features = np.array(
[[1., 1., 1., 1.],
[max, 1., 2., 3.]]).astype(type)
with self.test_session(use_gpu... | with self.assertRaises(ValueError): | random_line_split |
softmax_op_test.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 a... |
def testEmpty(self):
with self.test_session():
x = tf.constant([[]], shape=[0, 3])
self.assertEqual(0, tf.size(x).eval())
expected_y = np.array([]).reshape(0, 3)
np.testing.assert_array_equal(expected_y, tf.nn.softmax(x).eval())
if __name__ == "__main__":
tf.test.main()
| self._testSoftmax(
np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64),
use_gpu=False)
self._testOverflow(use_gpu=False) | identifier_body |
softmax_op_test.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 a... | (self, features, log=False):
batch_dim = 0
class_dim = 1
batch_size = features.shape[batch_dim]
e = np.exp(features -
np.reshape(np.amax(features, axis=class_dim), [batch_size, 1]))
softmax = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])
if log:
return np.log(so... | _npSoftmax | identifier_name |
kat.py | Rage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# bu... |
if self.confirmed and not verified:
logger.log(u"KAT Provider found result " + title + " but that doesn't seem like a verified result so I'm ignoring it", logger.DEBUG)
continue
if not title or not url:
... | logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG)
continue | conditional_block |
kat.py |
# (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of th... | # only poll KickAss every 10 minutes max | random_line_split | |
kat.py | Rage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# bu... | (generic.TorrentProvider):
def __init__(self):
generic.TorrentProvider.__init__(self, "KickAssTorrents")
self.supportsBacklog = True
self.public = True
self.enabled = False
self.confirmed = True
self.ratio = None
self.minseed = None
self.minleech = ... | KATProvider | identifier_name |
kat.py | Rage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# bu... |
def _get_episode_search_strings(self, ep_obj, add_string=''):
search_string = {'Episode': []}
for show_name in set(allPossibleShowNames(ep_obj.show)):
ep_string = sanitizeSceneName(show_name) + ' '
if ep_obj.show.air_by_date:
ep_string += str(ep_obj.airdate... | search_string = {'Season': []}
for show_name in set(allPossibleShowNames(ep_obj.show)):
ep_string = sanitizeSceneName(show_name) + ' '
if ep_obj.show.air_by_date or ep_obj.show.sports:
ep_string += str(ep_obj.airdate).split('-')[0]
elif ep_obj.show.anime:
... | identifier_body |
pending-account-deletion-page-root.component.ts | // Copyright 2021 The Oppia 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 ap... |
}
| {
this.pageHeadService.updateTitleAndMetaTags(
AppConstants.PAGES_REGISTERED_WITH_FRONTEND.PENDING_ACCOUNT_DELETION);
this.pageIsShown = true;
} | identifier_body |
pending-account-deletion-page-root.component.ts | // Copyright 2021 The Oppia 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 ap... | (): void {
this.pageHeadService.updateTitleAndMetaTags(
AppConstants.PAGES_REGISTERED_WITH_FRONTEND.PENDING_ACCOUNT_DELETION);
this.pageIsShown = true;
}
}
| ngOnInit | identifier_name |
pending-account-deletion-page-root.component.ts | // Copyright 2021 The Oppia 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 ap... | import { AppConstants } from 'app.constants';
import { PageHeadService } from 'services/page-head.service';
@Component({
selector: 'oppia-pending-account-deletion-page-root',
templateUrl: './pending-account-deletion-page-root.component.html'
})
export class PendingAccountDeletionPageRootComponent {
pageIsShown: ... | import { Component } from '@angular/core'; | random_line_split |
GitHubPullRequestsLoader.tsx | import gql from "graphql-tag"
import { createHttpLink, InMemoryCache, ApolloClient } from "@apollo/client"
import { EntryType } from "../models/Entry"
import Markdown from "../components/Markdown"
import ReactDOMServer from "react-dom/server"
import { LoaderEntriesCache } from "./LoaderEntriesCache"
import { GitHubPull... | (node) => node.topic.name,
),
)
const descriptionHTML = ReactDOMServer.renderToStaticMarkup(
<Markdown source={pullRequest.body} />,
)
return {
title: pullRequest.title,
descriptionHTML,
url: pullRequest.url,
slug: p... | )
.flatMap((pullRequest) => {
const tags = pullRequestTags.concat(
pullRequest.repository.repositoryTopics.nodes.map( | random_line_split |
GitHubPullRequestsLoader.tsx | import gql from "graphql-tag"
import { createHttpLink, InMemoryCache, ApolloClient } from "@apollo/client"
import { EntryType } from "../models/Entry"
import Markdown from "../components/Markdown"
import ReactDOMServer from "react-dom/server"
import { LoaderEntriesCache } from "./LoaderEntriesCache"
import { GitHubPull... | (): Promise<GitHubPullRequest[]> {
return this.cache.entries
}
private async loadPullRequests(): Promise<GitHubPullRequest[]> {
const accessToken = await loadSecret("GITHUB_ACCESS_TOKEN")
if (accessToken === undefined) {
console.warn(
"GITHUB_ACCESS_TOKEN is not set; GitHub pull requests... | getPullRequests | identifier_name |
GitHubPullRequestsLoader.tsx | import gql from "graphql-tag"
import { createHttpLink, InMemoryCache, ApolloClient } from "@apollo/client"
import { EntryType } from "../models/Entry"
import Markdown from "../components/Markdown"
import ReactDOMServer from "react-dom/server"
import { LoaderEntriesCache } from "./LoaderEntriesCache"
import { GitHubPull... |
const link = createHttpLink({
uri: "https://api.github.com/graphql",
fetch: fetch,
headers: {
Authorization: `bearer ${accessToken}`,
},
})
const client = new ApolloClient({
link: link,
cache: new InMemoryCache(),
})
console.debug("Loading GitHub pull re... | {
console.warn(
"GITHUB_ACCESS_TOKEN is not set; GitHub pull requests will not be loaded",
)
return []
} | conditional_block |
GitHubPullRequestsLoader.tsx | import gql from "graphql-tag"
import { createHttpLink, InMemoryCache, ApolloClient } from "@apollo/client"
import { EntryType } from "../models/Entry"
import Markdown from "../components/Markdown"
import ReactDOMServer from "react-dom/server"
import { LoaderEntriesCache } from "./LoaderEntriesCache"
import { GitHubPull... |
getPullRequests(): Promise<GitHubPullRequest[]> {
return this.cache.entries
}
private async loadPullRequests(): Promise<GitHubPullRequest[]> {
const accessToken = await loadSecret("GITHUB_ACCESS_TOKEN")
if (accessToken === undefined) {
console.warn(
"GITHUB_ACCESS_TOKEN is not set; G... | {
if (process.env["GITHUB_PULL_REQUESTS_TIMEOUT"] !== undefined) {
this.cache = new LoaderEntriesCache(
this.loadPullRequests.bind(this),
"GitHubPullRequests",
parseInt(process.env["GITHUB_PULL_REQUESTS_TIMEOUT"]),
)
} else if (process.env["CACHE_TIMEOUT"] !== undefined) {
... | identifier_body |
user.py | from flask import (Blueprint, request, session, g,
render_template, url_for, redirect, jsonify)
from werkzeug.contrib.cache import SimpleCache
from flask.ext.oauthlib.client import OAuth, OAuthException
bp = Blueprint('user', __name__)
oauth = OAuth()
github = oauth.remote_app(
'github', app_... | @bp.route('/login')
def login():
return github.authorize(callback=url_for('.authorized', _external=True))
@bp.route('/logout')
def logout():
session.pop('github_token', None)
return redirect(url_for('home.index'))
@bp.route('/login/authorized')
@github.authorized_handler
def authorized(response):
i... | """사용자가 GitHub 계정으로 인증한 상태인지 확인한다"""
try:
token, _ = session['github_token']
except KeyError:
g.user_info = None
return None
user_data = _cache.get('user_info:' + token)
if user_data is None:
try:
resp = github.get('user')
except OAuthException:
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.