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 |
|---|---|---|---|---|
test_expand_path.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib impor... | with self.root() as root:
with environment_as(A='B', C='D'):
self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E'))
@contextmanager
def root(self):
with temporary_dir() as root:
# Avoid OSX issues where tmp dirs are reported as symlinks.
real_root = os.path.realp... | self.assertEquals('/tmp/jake/bob', expand_path('~/bob'))
def test_env_var_expansion(self): | random_line_split |
test_expand_path.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib impor... |
def test_absolute(self):
self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob'))
def test_user_expansion(self):
with environment_as(HOME='/tmp/jake'):
self.assertEquals('/tmp/jake/bob', expand_path('~/bob'))
def test_env_var_expansion(self):
with self.root() as root:
with envi... | with self.root() as root:
self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) | identifier_body |
test_expand_path.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from contextlib impor... | (self):
self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob'))
def test_user_expansion(self):
with environment_as(HOME='/tmp/jake'):
self.assertEquals('/tmp/jake/bob', expand_path('~/bob'))
def test_env_var_expansion(self):
with self.root() as root:
with environment_as(A='B', C='... | test_absolute | identifier_name |
router.ts | import { assertType } from './lib/assert';
import Router from '@ember/routing/router';
import Service, { inject as service } from '@ember/service';
import EmberObject, { get } from '@ember/object';
const AppRouter = Router.extend({
});
AppRouter.map(function() {
this.route('index', { path: '/' });
this.route(... | ,
transitionWithModelAndOptions() {
const model = EmberObject.create();
get(this, 'router')
.transitionTo('index', model, { queryParams: { search: 'ember' }});
}
});
| {
const model = EmberObject.create();
get(this, 'router')
.transitionTo('some.other.route', model, model);
} | identifier_body |
router.ts | import { assertType } from './lib/assert';
import Router from '@ember/routing/router';
import Service, { inject as service } from '@ember/service';
import EmberObject, { get } from '@ember/object';
const AppRouter = Router.extend({
});
AppRouter.map(function() { | this.route('new');
this.route('post', { path: '/post/:post_id', resetNamespace: true });
this.route('comments', { resetNamespace: true }, function() {
this.route('new');
});
});
this.route('photo', { path: '/photo/:id' }, function() {
this.route('comment', { p... | this.route('index', { path: '/' });
this.route('about');
this.route('favorites', { path: '/favs' });
this.route('posts', function() {
this.route('index', { path: '/' }); | random_line_split |
router.ts | import { assertType } from './lib/assert';
import Router from '@ember/routing/router';
import Service, { inject as service } from '@ember/service';
import EmberObject, { get } from '@ember/object';
const AppRouter = Router.extend({
});
AppRouter.map(function() {
this.route('index', { path: '/' });
this.route(... | () {
get(this, 'router')
.transitionTo('some-route');
},
transitionWithModel() {
const model = EmberObject.create();
get(this, 'router')
.transitionTo('some.other.route', model);
},
transitionWithMultiModel() {
const model = EmberObject.create();
g... | transitionWithoutModel | identifier_name |
NotifyD7Networks.py | Invalid Argument(s) Specified.',
403: 'Unauthorized - Authentication Failure.',
412: 'A Routing Error Occured',
500: 'A Serverside Error Occured Handling the Request.',
}
# Some Phone Number Detection
IS_PHONE_NO = re.compile(r'^\+?(?P<phone>[0-9\s)(+-]+)\s*$')
# Priorities
class D7SMSPriority(object):
... | 'name': _('Target Phone No'),
'type': 'string',
'prefix': '+',
'regex': (r'^[0-9\s)(+-]+$', 'i'),
'map_to': 'targets',
},
'targets': {
'name': _('Targets'),
'type': 'list:string',
},
})
# Define our temp... | 'required': True,
},
'target_phone': { | random_line_split |
NotifyD7Networks.py | Argument(s) Specified.',
403: 'Unauthorized - Authentication Failure.',
412: 'A Routing Error Occured',
500: 'A Serverside Error Occured Handling the Request.',
}
# Some Phone Number Detection
IS_PHONE_NO = re.compile(r'^\+?(?P<phone>[0-9\s)(+-]+)\s*$')
# Priorities
class | (object):
"""
D7 Networks SMS Message Priority
"""
LOW = 0
MODERATE = 1
NORMAL = 2
HIGH = 3
D7NETWORK_SMS_PRIORITIES = (
D7SMSPriority.LOW,
D7SMSPriority.MODERATE,
D7SMSPriority.NORMAL,
D7SMSPriority.HIGH,
)
class NotifyD7Networks(NotifyBase):
"""
A wrapper for D7... | D7SMSPriority | identifier_name |
NotifyD7Networks.py | /secure/sendbatch'
# D7 Networks single notification URL
notify_url = 'http://rest-api.d7networks.com/secure/send'
# The maximum length of the body
body_maxlen = 160
# A title can not be used for SMS Messages. Setting this to zero will
# cause any title (if defined) to get placed into the me... | args['from'] = self.source | conditional_block | |
NotifyD7Networks.py | 'i'),
'map_to': 'targets',
},
'targets': {
'name': _('Targets'),
'type': 'list:string',
},
})
# Define our template arguments
template_args = dict(NotifyBase.template_args, **{
'priority': {
'name': _('Priority'),
... | """
Parses the URL and returns enough arguments that can allow
us to substantiate this object.
"""
results = NotifyBase.parse_url(url, verify_host=False)
if not results:
# We're done early as we couldn't load the results
return results
# Initial... | identifier_body | |
HomePage.e2e.ts | /* eslint jest/expect-expect: off, jest/no-test-callback: off */
import { ClientFunction, Selector } from 'testcafe';
const getPageUrl = ClientFunction(() => window.location.href);
const getPageTitle = ClientFunction(() => document.title);
const counterSelector = Selector('[data-tid="counter"]');
const buttonsSelector... | .afterEach(assertNoConsoleErrors);
test('should display updated count after the increment button click', async (t) => {
await t.click(incrementButton).expect(getCounterText()).eql('1');
});
test('should display updated count after the descrement button click', async (t) => {
await t.click(decrementButton).expec... | random_line_split | |
window.py | # 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/.
from datetime import datetime
from marionette_driver import By, Wait
from ..windows import BaseWindow
from ...api.soft... |
def check_for_updates(self):
"""Clicks on "Check for Updates" button, and waits for check to complete."""
self.deck.check_for_updates.button.click()
self.wait_for_check_finished()
def download(self, wait_for_finish=True, timeout=TIMEOUT_UPDATE_DOWNLOAD):
""" Download the updat... | """ Returns information about the active update in the queue.
:returns: A dictionary with information about the active patch
"""
patch = self._software_update.patch_info
patch['download_duration'] = self._download_duration
return patch | identifier_body |
window.py | # 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/.
from datetime import datetime
from marionette_driver import By, Wait
from ..windows import BaseWindow
from ...api.soft... |
# If there are incompatible addons we fallback on old software update dialog for updating
if self.deck.selected_panel == self.deck.apply_billboard:
# The rest of the code inside this method uses the update wizard which is
# not being converted yet, so raise a NotImplementedErro... | self.deck.download_and_install.button.click()
# Wait for the download to start
Wait(self.marionette).until(
lambda _: self.deck.selected_panel != self.deck.download_and_install) | conditional_block |
window.py | # 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/.
from datetime import datetime
from marionette_driver import By, Wait
from ..windows import BaseWindow
from ...api.soft... |
:returns: Reference to the deck.
"""
deck = self.window_element.find_element(By.ID, 'updateDeck')
return Deck(lambda: self.marionette, self, deck)
@property
def patch_info(self):
""" Returns information about the active update in the queue.
:returns: A dictiona... | random_line_split | |
window.py | # 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/.
from datetime import datetime
from marionette_driver import By, Wait
from ..windows import BaseWindow
from ...api.soft... | (self):
""" Returns information about the active update in the queue.
:returns: A dictionary with information about the active patch
"""
patch = self._software_update.patch_info
patch['download_duration'] = self._download_duration
return patch
def check_for_updates(... | patch_info | identifier_name |
crawler.component.ts | crawledData: any[] = [];
done = false;
fail = false;
dots = "";
private d3: D3; // <-- Define the private member which will hold the d3 reference
parentNativeElement: any;
constructor(private route: ActivatedRoute, d3Service: D3Service, element: ElementRef) {
this.d3 = d3Service.getD3();
this.par... |
self.root = self.d3.hierarchy(self.crawledTrees, function (d) {
return d.children;
});
let margin = {top: 20, right: 90, bottom: 30, left: 90},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
... | {
this.doD3();
setInterval(() => {
if (this.dots.length > 6) {
this.dots = "";
} else {
this.dots += "."
}
}, 200);
let self = this;
this.route.params
.subscribe(params => {
this.targetSite = params.hostname;
oboe("/api/crawl?site=" + this.... | identifier_body |
crawler.component.ts | let result = ["/"];
if (path == "/") {
return result
}
result.push(...path.split("/"));
return result.filter(function (p) {
return p != "";
});
}
previousNumber = 0;
currentTree: any = {
pathPiece: "/",
name: "/",
children: []
};
get crawledTrees() {
if (t... | {
d._children = d.children;
d._children.forEach(this.collapse);
d.children = null
} | conditional_block | |
crawler.component.ts | false;
fail = false;
dots = "";
private d3: D3; // <-- Define the private member which will hold the d3 reference
parentNativeElement: any;
constructor(private route: ActivatedRoute, d3Service: D3Service, element: ElementRef) {
this.d3 = d3Service.getD3();
this.parentNativeElement = element.nativeEl... | });
| random_line_split | |
crawler.component.ts | implements OnInit {
targetSite: String;
crawledData: any[] = [];
done = false;
fail = false;
dots = "";
private d3: D3; // <-- Define the private member which will hold the d3 reference
parentNativeElement: any;
constructor(private route: ActivatedRoute, d3Service: D3Service, element: ElementRef) {
... | CrawlerComponent | identifier_name | |
image_provider.py | # Copyright (c) 2016 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 applic... | if settings.use_jpeg == 1:
img = image_util.decode_jpeg(data['images'][i])
else:
img = data['images'][i]
img_feat = image_util.preprocess_img(
img, settings.img_mean, settings.img_size,
... | conditional_block | |
image_provider.py | # Copyright (c) 2016 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 applic... | settings.mean_img_size = mean_img_size
settings.img_size = img_size
settings.num_classes = num_classes
settings.color = color
settings.is_train = is_train
if settings.color:
settings.img_raw_size = settings.img_size * settings.img_size * 3
else:
settings.img_raw_size = setti... | def hook(settings, img_size, mean_img_size, num_classes, color, meta, use_jpeg,
is_train, **kwargs): | random_line_split |
image_provider.py | # Copyright (c) 2016 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 applic... | (settings, file_list):
"""
The main function for loading data.
Load the batch, iterate all the images and labels in this batch.
file_list: the batch file list.
"""
with open(file_list, 'r') as fdata:
lines = [line.strip() for line in fdata]
random.shuffle(lines)
for file_... | processData | identifier_name |
image_provider.py | # Copyright (c) 2016 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 applic... | settings.input_types = {
'image': dense_vector(settings.img_raw_size),
'label': integer_value(settings.num_classes)
}
settings.logger.info('DataProvider Initialization finished')
@provider(init_hook=hook, min_pool_size=0)
def processData(settings, file_list):
"""
The main functio... | settings.mean_img_size = mean_img_size
settings.img_size = img_size
settings.num_classes = num_classes
settings.color = color
settings.is_train = is_train
if settings.color:
settings.img_raw_size = settings.img_size * settings.img_size * 3
else:
settings.img_raw_size = settings.... | identifier_body |
detail-small.js | /************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
* | * (at your option) any later version.
*
* EspoCRM 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... | * EspoCRM 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 | random_line_split |
package_spec.js | var search = require('./helpers/search'),
authoring = require('./helpers/pages').authoring,
monitoring = require('./helpers/monitoring');
describe('package', () => {
beforeEach(() => {
monitoring.openMonitoring();
});
it('increment package version', () => {
monitoring.actionOnItem(... | monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
// Open menu.
var menu = monitoring.openItemMenu(2, 0);
var header = menu.element(by.partialLinkText('Add to current'));
expect(header.isPresent()).toBeFalsy();
// Close menu.
menu.element(by.css('.d... | random_line_split | |
serverSocket.ts | new Error(`No server for given id (${id})`);
}
function verifyClient({ req }: { req: IncomingMessage }, next: (result: any, code: number, name: string) => void) {
try {
const query = getQuery(req.url);
const server = getServer(query.id);
if (!server.verifyClient(req)) {
next(false, errorCod... |
function connectSocket(socket: ws, request: IncomingMessage) {
try {
const originalRequest = createOriginalRequest(socket, request);
const query = getQuery(originalRequest.url);
const server = getServer(query.id);
connectClient(socket, server, originalRequest, errorHandler, log);
} catch (e) {
... | }
socket.destroy();
}
});
}
| random_line_split |
serverSocket.ts | 200, 'OK');
}
} catch (e) {
errorHandler.handleError(null, e);
next(false, errorCode, errorName);
}
}
function close() {
servers.forEach(closeServer);
wsServer.close();
}
function closeAndRemoveServer(server: InternalServer) {
closeServer(server);
const index = servers.indexOf(... | disconnect | identifier_name | |
serverSocket.ts | }
function verifyClient({ req }: { req: IncomingMessage }, next: (result: any, code: number, name: string) => void) {
try {
const query = getQuery(req.url);
const server = getServer(query.id);
if (!server.verifyClient(req)) {
next(false, errorCode, errorName);
} else if (server.clientLimi... | {
const query = getQuery(originalRequest.url);
const t = (query.t || '') as string;
const token = server.connectionTokens ? getToken(server, t) || getTokenFromClient(server, t) : undefined;
if (server.connectionTokens && !token) {
errorHandler.handleError({ originalRequest } as any, new Error(`Invalid toke... | identifier_body | |
logger.ts | import * as _ from 'underscore'
import * as Koa from "koa"
import * as logger from '@nodeswork/logger'
import { NodesworkComponent, NodesworkComponentOption } from './component'
let LOG = logger.getLogger('logger');
| requestLog: any
}
export interface LoggerClass {
new(ctx: LoggerKoaContext): Logger;
}
export class Logger extends NodesworkComponent<LoggerKoaContext> {
private getMeta(meta: any): any {
return _.extend({ key: this.ctx.logKey }, meta);
}
request(data: {}): void {
_.extend(this.ctx.requestLog, ... | export interface LoggerKoaContext extends Koa.Context {
logKey: string | random_line_split |
logger.ts | import * as _ from 'underscore'
import * as Koa from "koa"
import * as logger from '@nodeswork/logger'
import { NodesworkComponent, NodesworkComponentOption } from './component'
let LOG = logger.getLogger('logger');
export interface LoggerKoaContext extends Koa.Context {
logKey: string
requestLog: any
}
... | (ctx: LoggerKoaContext, next: Function): Promise<void> {
ctx.requestLog = {
header: {
path: ctx.request.path,
method: ctx.request.method,
}
};
let responseCode: number;
try {
await next();
responseCode = ctx.response.status;
} catch (e) {
responseCode = 500;
throw e;
... | setupRequestLog | identifier_name |
logger.ts | import * as _ from 'underscore'
import * as Koa from "koa"
import * as logger from '@nodeswork/logger'
import { NodesworkComponent, NodesworkComponentOption } from './component'
let LOG = logger.getLogger('logger');
export interface LoggerKoaContext extends Koa.Context {
logKey: string
requestLog: any
}
... |
request(data: {}): void {
_.extend(this.ctx.requestLog, data);
}
debug(message: string, meta={}): void {
LOG.debug(message, this.getMeta(meta));
}
verbose(message: string, meta={}): void {
LOG.verbose(message, this.getMeta(meta));
}
info(message: string, meta={}): void {
LOG.info(mess... | {
return _.extend({ key: this.ctx.logKey }, meta);
} | identifier_body |
pager.js | // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
'base/js/namespace',
'jqueryui',
'base/js/utils',
], function(IPython, $, utils) {
"use strict";
var Pager = function (pager_selector, options) {
/**
* Constructor
... | // notebook.
$('.end_space').css('height', Math.max(this.pager_element.height(), this._default_end_space));
};
// Backwards compatability.
IPython.Pager = Pager;
return {'Pager': Pager};
}); | */
// Make sure the padding at the end of the notebook is large
// enough that the user can scroll to the bottom of the | random_line_split |
pager.js | // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
'base/js/namespace',
'jqueryui',
'base/js/utils',
], function(IPython, $, utils) {
"use strict";
var Pager = function (pager_selector, options) {
/**
* Constructor
... |
};
Pager.prototype.expand = function (extrap) {
if (this.expanded !== true) {
this.expanded = true;
this.pager_element.trigger('expand_pager', extrap);
}
};
Pager.prototype.toggle = function () {
if (this.expanded === true) {
this.collapse... | {
this.expanded = false;
this.pager_element.trigger('collapse_pager', extrap);
} | conditional_block |
Summary.ts | /*
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the \"Software\"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modi... |
} | {
super(idOrAttributesOrElement, Summary.SUMMARY);
} | identifier_body |
Summary.ts | /*
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the \"Software\"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modi... | class Summary extends Container<Summary, HTMLElement> implements IHtml5
{
public static SUMMARY: string = 'summary';
constructor();
constructor(id: string)
constructor(attributes: Object)
constructor(element: HTMLElement)
constructor(idOrAttributesOrElement?: any) {
super(idOrAttributesOrElement, Summary.... | *
* @class Summary
* @extends Container
* @constructor
**/ | random_line_split |
Summary.ts | /*
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the \"Software\"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modi... | extends Container<Summary, HTMLElement> implements IHtml5
{
public static SUMMARY: string = 'summary';
constructor();
constructor(id: string)
constructor(attributes: Object)
constructor(element: HTMLElement)
constructor(idOrAttributesOrElement?: any) {
super(idOrAttributesOrElement, Summary.SUMMARY);
} ... | Summary | identifier_name |
location.rs | header! {
/// `Location` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.1.2)
///
/// The `Location` header field is used in some responses to refer to a
/// specific resource in relation to the response. The type of
/// relationship is defined by the combination o... | test_header!(test2, vec![b"http://www.example.net/index.html"]);
}
}
bench_header!(bench, Location, { vec![b"http://foo.com/hello:3000".to_vec()] }); | // Testcase from RFC
test_header!(test1, vec![b"/People.html#tim"]); | random_line_split |
usererrorhandler.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | def run(self, *args):
raise DataError(self.error) | def init_keyword(self, varz):
pass
| random_line_split |
usererrorhandler.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... |
def init_keyword(self, varz):
pass
def run(self, *args):
raise DataError(self.error)
| return '%s.%s' % (self.libname, self.name) if self.libname else self.name | identifier_body |
usererrorhandler.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | (self):
return '%s.%s' % (self.libname, self.name) if self.libname else self.name
def init_keyword(self, varz):
pass
def run(self, *args):
raise DataError(self.error)
| longname | identifier_name |
__openerp__.py | # Copyright 2015 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This progr... | # Author: Leonardo Pistone | random_line_split | |
pps_matchup.py | SAT_FIELDS['viirs'] = ['sunz', 'satz', 'ssazd', 'ciwv', 'tsur', 'm05',
'm07', 'm09', 'm10', 'm11', 'm12', 'm14', 'm15', 'm16']
SAT_FIELDS['avhrr'] = ['sunz', 'satz', 'ssazd', 'cwiv', 'tsur', '1',
'2', '3a', '3b', 'dummy', '4', '5']
CTYPE_PATTERN = "S_NWC_CT_{satellite:s}_{... | SAT_FIELDS = {} | random_line_split | |
pps_matchup.py | kwargs # Not used atm
geodata = np.vstack((self.avhrr.area.lons.ravel(),
self.avhrr.area.lats.ravel())).T
kd_tree = KDTree(geodata)
satdata_shape = self.avhrr.area.lons.shape
try:
corners = self.avhrr.area.corners
clons = np.array(... | matchstr = os.path.join(ROOTDIR,
"export/S_NWC_CT_%s_?????_%sT*_*Z.h5" % (satellite, tslot.strftime('%Y%m%d'))) | conditional_block | |
pps_matchup.py | %.1d' % idx):
obj = getattr(sunsat_angles, 'image%.1d' % idx)
info = getattr(obj, 'info')
for angle_name in ANGLE_NAMES:
if info['product'] == angle_name:
dname = angle_name.lower()
value = getattr(obj, 'data')[point[0], point[1... | ncl = np.sum(np.logical_and(np.greater(ctyarr, 4),
np.less(ctyarr, 20)))
ntot = np.sum(np.logical_and(ctyarr != 0, ctyarr != 20))
if ntot == 0:
return None, center_val
return float(ncl) / float(ntot), center_val
def mask_bounds(boundary, nodata=None):
"""M... | """Get the cloud cover around the pixel *point* using a box with dimensions
*box* """
try:
ctypedata = pps_ctype.cloudtype.data
except AttributeError:
ctypedata = pps_ctype.ct.data
shape = ctypedata.shape
center_val = ctypedata[point[0], point[1]]
y_left, y_right = point[0] -... | identifier_body |
pps_matchup.py | 1d' % idx):
obj = getattr(sunsat_angles, 'image%.1d' % idx)
info = getattr(obj, 'info')
for angle_name in ANGLE_NAMES:
if info['product'] == angle_name:
dname = angle_name.lower()
value = getattr(obj, 'data')[point[0], point[1]]... | (pps_ctype, point, box):
"""Get the cloud cover around the pixel *point* using a box with dimensions
*box* """
try:
ctypedata = pps_ctype.cloudtype.data
except AttributeError:
ctypedata = pps_ctype.ct.data
shape = ctypedata.shape
center_val = ctypedata[point[0], point[1]]
... | get_cloud_cover | identifier_name |
RangeThresholdMarkers.tsx | // Libraries
import React, {FunctionComponent, MouseEvent} from 'react'
import {Scale} from '@influxdata/giraffe'
// Components
import ThresholdMarker from 'src/shared/components/ThresholdMarker'
import ThresholdMarkerArea from 'src/shared/components/ThresholdMarkerArea'
// Utils
import {isInDomain, clamp} from 'src/... | level={level}
top={minY}
height={yScale(yDomain[0]) - minY}
/>
)}
</>
)}
</>
)
}
export default RangeThresholdMarkers | {min >= yDomain[0] && (
<ThresholdMarkerArea | random_line_split |
test_images.py | # Copyright 2018 Red Hat, 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... | # NOTE: Create image with owner different from tenant owner by
# using "owner" parameter requires an admin privileges.
random_id = data_utils.rand_uuid_hex()
image = self.admin_client.create_image(
container_format='bare', disk_format='raw', owner=random_id)
self.addC... | @decorators.related_bug('1420008')
@decorators.idempotent_id('646a6eaa-135f-4493-a0af-12583021224e')
def test_create_image_owner_param(self): | random_line_split |
test_images.py | # Copyright 2018 Red Hat, 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... | (self):
random_id_1 = data_utils.rand_uuid_hex()
image = self.admin_client.create_image(
container_format='bare', disk_format='raw', owner=random_id_1)
self.addCleanup(self.admin_client.delete_image, image['id'])
created_image_info = self.admin_client.show_image(image['id'])
... | test_update_image_owner_param | identifier_name |
test_images.py | # Copyright 2018 Red Hat, 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... |
@decorators.related_bug('1420008')
@decorators.idempotent_id('525ba546-10ef-4aad-bba1-1858095ce553')
def test_update_image_owner_param(self):
random_id_1 = data_utils.rand_uuid_hex()
image = self.admin_client.create_image(
container_format='bare', disk_format='raw', owner=rando... | random_id = data_utils.rand_uuid_hex()
image = self.admin_client.create_image(
container_format='bare', disk_format='raw', owner=random_id)
self.addCleanup(self.admin_client.delete_image, image['id'])
image_info = self.admin_client.show_image(image['id'])
self.assertEqual(ran... | identifier_body |
webpack.config.test.js | /*eslint-disable */
var webpack = require( "webpack" );
var sml = require( "source-map-loader" );
/*eslint-enable */
var path = require( "path" );
module.exports = {
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
}
],
loaders: [
{ test: /sinon.*\.js/, loader: "imports?defi... | "when.pipeline": "when/pipeline",
react: "react/dist/react-with-addons.js",
lux: path.join( __dirname, "./lib/lux.js" )
}
}
}; | resolve: {
alias: {
"when.parallel": "when/parallel", | random_line_split |
domrect.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::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec... |
}
| {
self.rect.set_height(value);
} | identifier_body |
domrect.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::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec... | (&self) -> f64 {
self.rect.Width()
}
// https://drafts.fxtf.org/geometry/#dom-domrect-width
fn SetWidth(&self, value: f64) {
self.rect.set_width(value);
}
// https://drafts.fxtf.org/geometry/#dom-domrect-height
fn Height(&self) -> f64 {
self.rect.Height()
}
// ... | Width | identifier_name |
domrect.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::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRec... | impl DOMRect {
fn new_inherited(x: f64, y: f64, width: f64, height: f64) -> DOMRect {
DOMRect {
rect: DOMRectReadOnly::new_inherited(x, y, width, height),
}
}
pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> DomRoot<DOMRect> {
reflect_dom_obje... | rect: DOMRectReadOnly,
}
| random_line_split |
dashboard-create.ts | import Dashboard from '../../models/dashboard'
import manager from '../manager'
import { make } from '../../models/items/factory'
declare var $, window
/*
* Logic for the dashboard-create.html template.
*/
$(document).ready(function() {
let tags = $('#ds-dashboard-tags')
if (tags.length) |
})
$(document).ready(function() {
let form = $('#ds-dashboard-create-form')
if (form.length) {
form.bootstrapValidator()
}
})
$(document).on('click', '#ds-new-dashboard-create', function(e) {
let title = $('#ds-dashboard-title')[0].value
let category = $('#ds-dashboard-category')[0].value
let summa... | {
tags .tagsManager({
tagsContainer: '.ds-tag-holder',
tagClass: 'badge badge-primary'
})
} | conditional_block |
dashboard-create.ts | import Dashboard from '../../models/dashboard'
import manager from '../manager'
import { make } from '../../models/items/factory'
declare var $, window
/*
* Logic for the dashboard-create.html template.
*/
$(document).ready(function() {
let tags = $('#ds-dashboard-tags')
if (tags.length) {
tags .tagsManage... | }) | $(document).on('click', '#ds-new-dashboard-cancel', function(e) {
window.history.back() | random_line_split |
woff_metadata_license_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum WoffMetadataLicenseOffset {}
#[derive(Copy, Clone, PartialEq)]
| pub struct WoffMetadataLicense<'a> {
pub _tab: flatbuffers::Table<'a>,
}
impl<'a> flatbuffers::Follow<'a> for WoffMetadataLicense<'a> {
type Inner = WoffMetadataLicense<'a>;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
Self { _tab: flatbuffers::Table { buf, loc } }
}
}
impl<'a> WoffMe... | random_line_split | |
woff_metadata_license_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum WoffMetadataLicenseOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct WoffMetadataLicense<'a> {
pub _tab: fla... |
builder.finish()
}
#[inline]
pub fn url(&self) -> Option<&'a str> {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(WoffMetadataLicense::VT_URL, None)
}
#[inline]
pub fn id(&self) -> Option<&'a str> {
self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(WoffMetadataLicense::VT_ID, None)
... | { builder.add_url(x); } | conditional_block |
woff_metadata_license_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum WoffMetadataLicenseOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct WoffMetadataLicense<'a> {
pub _tab: fla... |
}
pub struct WoffMetadataLicenseArgs<'a> {
pub url: Option<flatbuffers::WIPOffset<&'a str>>,
pub id: Option<flatbuffers::WIPOffset<&'a str>>,
pub text: Option<flatbuffers::WIPOffset<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<WoffMetadataText<'a>>>>>,
}
impl<'a> Default for WoffMetadataLicenseArgs... | {
use self::flatbuffers::Verifiable;
v.visit_table(pos)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>("url", Self::VT_URL, false)?
.visit_field::<flatbuffers::ForwardsUOffset<&str>>("id", Self::VT_ID, false)?
.visit_field::<flatbuffers::ForwardsUOffset<flatbuffers::Vector<'_, flatbuffers::F... | identifier_body |
woff_metadata_license_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
pub enum WoffMetadataLicenseOffset {}
#[derive(Copy, Clone, PartialEq)]
pub struct WoffMetadataLicense<'a> {
pub _tab: fla... | (self) -> flatbuffers::WIPOffset<WoffMetadataLicense<'a>> {
let o = self.fbb_.end_table(self.start_);
flatbuffers::WIPOffset::new(o.value())
}
}
impl std::fmt::Debug for WoffMetadataLicense<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("WoffMetad... | finish | identifier_name |
en.js | editAreaLoader.lang["en"]={
new_document: "new empty document",
search_button: "search and replace",
search_command: "search next / open search area",
search: "search",
replace: "replace",
replace_command: "replace / open search area",
find_next: "find next",
replace_all: "replace all",
reg_exp: "regular expre... | not_found: "not found.",
occurrence_replaced: "occurences replaced.",
search_field_empty: "Search field empty",
restart_search_at_begin: "End of area reached. Restart at begin.",
move_popup: "move search popup",
font_size: "--Font size--",
go_to_line: "go to line",
go_to_line_prompt: "go to line number:",
undo:... | random_line_split | |
build.test.ts | import execa from 'execa';
import * as fs from 'fs-extra';
import { ExitError } from '../utils';
import {
basicKeystoneConfig,
cliBinPath,
js,
recordConsole,
runCommand,
schemas,
symlinkKeystoneDeps,
testdir,
} from './utils';
// the general success cases for build and start are tested in the example s... | `);
expect(result.exitCode).toBe(0);
}); | ○ (Static) automatically rendered as static HTML (uses no initial props)
" | random_line_split |
managed-pointer-within-unique.rs | // Copyright 2013 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 ... | () {()}
| zzz | identifier_name |
managed-pointer-within-unique.rs | // Copyright 2013 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 ... |
// compile-flags:-Z extra-debug-info
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print *ordinary_unique
// check:$1 = {-1, -2}
// debugger:print managed_within_unique.val->x
// check:$2 = -3
// debugger:print managed_within_unique.val->y->val
// check:$3 = ... |
// xfail-android: FIXME(#10381)
#[feature(managed_boxes)]; | random_line_split |
saveAction.ts | import { ActionContextType } from '../../context.type'
import * as check from 'check-types'
export const saveAction =
( { state
, input: { doc, docs }
, services: { data: { db } }
, output
} : ActionContextType
) => {
if ( docs ) |
else if ( doc ) {
// setTimeout ( () => {
db.put
( doc
, ( err ) => {
if ( err ) {
output.error
( { status: { type: 'error', message: err.message } } )
}
else {
output.success
( { status: { type: 'success', message: `Saved ${doc.type}` ... | {
db.bulkDocs
( docs
, ( err ) => {
if ( err ) {
output.error
( { status: { type: 'error', message: err } } )
}
else {
output.success
( { status:
{ type: 'success'
, message: `Saved ${docs [ 0 ].type}`
... | conditional_block |
saveAction.ts | import { ActionContextType } from '../../context.type'
import * as check from 'check-types'
export const saveAction =
( { state
, input: { doc, docs }
, services: { data: { db } }
, output
} : ActionContextType
) => {
if ( docs ) {
db.bulkDocs
( docs
, ( err ) => {
if ( err ) {
... |
}
saveAction [ 'async' ] = true
// Cerebral type checking
const mdoc = { _id: 'string', type: 'string' }
saveAction [ 'input' ] = ( v ) => {
return check.maybe.like ( v.doc, mdoc )
&& check.maybe.array.of.like ( v.docs, mdoc )
} | } | random_line_split |
translation.rs | use register::{Word, SysResult, Original, Modified, StackPointer};
use kernel::{enter, exit};
use process::proot::InfoBag;
use process::tracee::{TraceeStatus, TraceeRestartMethod, Tracee};
pub trait SyscallTranslator {
fn translate_syscall(&mut self, info_bag: &InfoBag);
fn translate_syscall_enter(&mut self, i... | // status = notify_extensions(tracee, SYSCALL_EXIT_START, 0, 0);
// if (status < 0) {
// poke_reg(tracee, SYSARG_RESULT, (word_t) status);
// goto end;
// }
// if (status > 0)
// return;
if self.status.is_ok() {
exit::translate(sel... | fn translate_syscall_exit(&mut self) {
// By default, restore original register values at the end of this stage.
self.regs.set_restore_original_regs(true);
//TODO: notify extensions for SYSCALL_EXIT_START event | random_line_split |
translation.rs | use register::{Word, SysResult, Original, Modified, StackPointer};
use kernel::{enter, exit};
use process::proot::InfoBag;
use process::tracee::{TraceeStatus, TraceeRestartMethod, Tracee};
pub trait SyscallTranslator {
fn translate_syscall(&mut self, info_bag: &InfoBag);
fn translate_syscall_enter(&mut self, i... |
//TODO: notify extensions for SYSCALL_EXIT_END event
// status = notify_extensions(tracee, SYSCALL_EXIT_END, 0, 0);
// if (status < 0)
// poke_reg(tracee, SYSARG_RESULT, (word_t) status);
// reset the tracee's status
self.status = TraceeStatus::SysEnter;
}
}
| {
self.regs.set(
SysResult,
self.status.get_errno() as Word,
"following previous error in enter stage, setting errno",
);
} | conditional_block |
translation.rs | use register::{Word, SysResult, Original, Modified, StackPointer};
use kernel::{enter, exit};
use process::proot::InfoBag;
use process::tracee::{TraceeStatus, TraceeRestartMethod, Tracee};
pub trait SyscallTranslator {
fn translate_syscall(&mut self, info_bag: &InfoBag);
fn translate_syscall_enter(&mut self, i... | // status2 = notify_extensions(tracee, SYSCALL_ENTER_END, status, 0);
// if (status2 < 0)
// status = status2;
// Saving the registers potentially modified by the translation.
// It's useful in order to know what the translation did to the registers.
self.regs.save_c... | {
// Never restore original register values at the end of this stage.
self.regs.set_restore_original_regs(false);
// Saving the original registers here.
// It is paramount in order to restore the regs after the exit stage,
// and also as memory in order to remember the original ... | identifier_body |
translation.rs | use register::{Word, SysResult, Original, Modified, StackPointer};
use kernel::{enter, exit};
use process::proot::InfoBag;
use process::tracee::{TraceeStatus, TraceeRestartMethod, Tracee};
pub trait SyscallTranslator {
fn translate_syscall(&mut self, info_bag: &InfoBag);
fn translate_syscall_enter(&mut self, i... | (&mut self, info_bag: &InfoBag) {
if let Err(error) = self.regs.fetch_regs() {
eprintln!("proot error: Error while fetching regs: {}", error);
return;
}
match self.status {
TraceeStatus::SysEnter => self.translate_syscall_enter(info_bag),
TraceeSt... | translate_syscall | identifier_name |
textlint-rule-alex.js | // LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import alex from "alex";
const defaultOptions = {
allow: undefined,
deny: undefined,
noBinary: false,
profanitySureness: 0
};
module.exports = function textlintRuleAlex(context, options = {}) {
const {Syntax, RuleError, ... | (node){
if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
return;
}
const text = getSource(node);
const messages = alex(text, opts).messages;
messages.forEach((result) => {
reportEr... | [Syntax.Str] | identifier_name |
textlint-rule-alex.js | // LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import alex from "alex";
const defaultOptions = {
allow: undefined,
deny: undefined,
noBinary: false,
profanitySureness: 0
};
module.exports = function textlintRuleAlex(context, options = {}) {
const {Syntax, RuleError, ... |
const text = getSource(node);
const messages = alex(text, opts).messages;
messages.forEach((result) => {
reportError(node, result);
});
}
}
} | {
return;
} | conditional_block |
textlint-rule-alex.js | // LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import alex from "alex";
const defaultOptions = {
allow: undefined,
deny: undefined,
noBinary: false,
profanitySureness: 0
};
module.exports = function textlintRuleAlex(context, options = {}) {
const {Syntax, RuleError, ... | [Syntax.Str](node){
if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
return;
}
const text = getSource(node);
const messages = alex(text, opts).messages;
messages.forEach((result) => {
... | report(node, ruleError);
};
return { | random_line_split |
textlint-rule-alex.js | // LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import alex from "alex";
const defaultOptions = {
allow: undefined,
deny: undefined,
noBinary: false,
profanitySureness: 0
};
module.exports = function textlintRuleAlex(context, options = {}) {
const {Syntax, RuleError, ... |
}
} | {
if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
return;
}
const text = getSource(node);
const messages = alex(text, opts).messages;
messages.forEach((result) => {
reportError(no... | identifier_body |
PersonalFiles.js | )
this.handleCancelRestore = this.handleCancelRestore.bind(this)
this.handleValidateRestore = this.handleValidateRestore.bind(this)
this.store = new Store()
this.state = {
searchTerm: '',
matchingFiles: [],
target_directory: '/',
refresh: 0,
lock: false,
}
}
compon... | <a key={file.path} onClick={(event) => {
if(selected.length === 0) {
if(file.type === 'folder') {
this.setState(Object.assign(this.state, {target_directory: file.path}))
} else {
openFile(file)
}
} else {
... | const hidden = (selected.length === 0) ? 'hidden' : ''
var selected_file = this.isSelected(file)
return ( | random_line_split |
PersonalFiles.js | extends Component {
constructor(props) {
super(props)
this.onSearchInputChange = this.onSearchInputChange.bind(this)
this.selectFile = this.selectFile.bind(this)
this.isSelected = this.isSelected.bind(this)
this.refresh = this.refresh.bind(this)
this.handleCancelRestore = this.handleCancelRe... | PersonalFiles | identifier_name | |
test_json.py | """Test Home Assistant json utility functions."""
from json import JSONEncoder
import os
import sys
from tempfile import mkdtemp
import unittest
from unittest.mock import Mock
import pytest
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.json import SerializationError, load_json, save_... |
def test_save_and_load():
"""Test saving and loading back."""
fname = _path_for("test1")
save_json(fname, TEST_JSON_A)
data = load_json(fname)
assert data == TEST_JSON_A
# Skipped on Windows
@unittest.skipIf(
sys.platform.startswith("win"), "private permissions not supported on Windows"
)
d... | return os.path.join(TMP_DIR, leaf_name + ".json") | identifier_body |
test_json.py | """Test Home Assistant json utility functions."""
from json import JSONEncoder
import os
import sys
from tempfile import mkdtemp
import unittest
from unittest.mock import Mock
import pytest
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.json import SerializationError, load_json, save_... |
def test_save_bad_data():
"""Test error from trying to save unserialisable data."""
fname = _path_for("test4")
with pytest.raises(SerializationError):
save_json(fname, TEST_BAD_OBJECT)
def test_load_bad_data():
"""Test error from trying to load unserialisable data."""
fname = _path_for("... | fname = _path_for("test3")
save_json(fname, TEST_JSON_A)
save_json(fname, TEST_JSON_B)
data = load_json(fname)
assert data == TEST_JSON_B | random_line_split |
test_json.py | """Test Home Assistant json utility functions."""
from json import JSONEncoder
import os
import sys
from tempfile import mkdtemp
import unittest
from unittest.mock import Mock
import pytest
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.json import SerializationError, load_json, save_... | ():
"""Test that we can overwrite an existing file and read back."""
fname = _path_for("test3")
save_json(fname, TEST_JSON_A)
save_json(fname, TEST_JSON_B)
data = load_json(fname)
assert data == TEST_JSON_B
def test_save_bad_data():
"""Test error from trying to save unserialisable data."""... | test_overwrite_and_reload | identifier_name |
test_json.py | """Test Home Assistant json utility functions."""
from json import JSONEncoder
import os
import sys
from tempfile import mkdtemp
import unittest
from unittest.mock import Mock
import pytest
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.json import SerializationError, load_json, save_... |
os.rmdir(TMP_DIR)
def _path_for(leaf_name):
return os.path.join(TMP_DIR, leaf_name + ".json")
def test_save_and_load():
"""Test saving and loading back."""
fname = _path_for("test1")
save_json(fname, TEST_JSON_A)
data = load_json(fname)
assert data == TEST_JSON_A
# Skipped on Windows
... | os.remove(os.path.join(TMP_DIR, fname)) | conditional_block |
index.js | import React from 'react'
import Button from 'components/Button'
import Flex from 'components/Flex'
import { Explanation, TextStep, Buttons } from '../styles'
import explanation from 'images/bearing-explanation.svg'
export class Step extends React.Component {
render () {
return (
<TextStep>
<div... | <p>
<Explanation alt='Camera and target' title='Camera and target' src={explanation} />
</p>
</div>
<Buttons>
<Flex justifyContent='flex-end'>
<Button onClick={this.props.skip} type='skip'>Skip</Button>
<Button onClick={this.props.next} t... | If it’s clear which way the camera is pointing, you can go to the next
step and try marking the direction and angle of the view of the image.
</p> | random_line_split |
index.js | import React from 'react'
import Button from 'components/Button'
import Flex from 'components/Flex'
import { Explanation, TextStep, Buttons } from '../styles'
import explanation from 'images/bearing-explanation.svg'
export class | extends React.Component {
render () {
return (
<TextStep>
<div>
<h2>Thanks!</h2>
<p>
If it’s clear which way the camera is pointing, you can go to the next
step and try marking the direction and angle of the view of the image.
</p>
<p>... | Step | identifier_name |
analytics.hooks.js | var MethodsAvailable = {
removeFilter : removeFilter,
applyFilters : applyFilters,
addFilter : addFilter,
removeAction : removeAction,
doAction : doAction,
addAction : addAction
};
/**
* Contains the hooks that get registered with this EventManager. The array for storage utilizes a... |
else {
for ( i = handlers.length; i--; ) {
var handler = handlers[i];
if ( handler.callback === callback && handler.context === context) {
handlers.splice( i, 1 );
}
}
}
}
}
/**
* Adds the hook to the appropriate storage container
*
* @param ty... | {
for ( i = handlers.length; i--; ) {
if ( handlers[i].callback === callback ) {
handlers.splice( i, 1 );
}
}
} | conditional_block |
analytics.hooks.js | var MethodsAvailable = {
removeFilter : removeFilter,
applyFilters : applyFilters,
addFilter : addFilter,
removeAction : removeAction,
doAction : doAction,
addAction : addAction
};
/**
* Contains the hooks that get registered with this EventManager. The array for storage utilizes a... |
/**
* Removes the specified hook by resetting the value of it.
*
* @param type Type of hook, either 'actions' or 'filters'
* @param hook The hook (namespace.identifier) to remove
* @private
*/
function _removeHook( type, hook, callback, context ) {
if ( !STORAGE[ type ][ hook ] ) {
... | {
if( typeof filter === 'string') {
_removeHook( 'filters', filter, callback );
}
return MethodsAvailable;
} | identifier_body |
analytics.hooks.js | */
var MethodsAvailable = {
removeFilter : removeFilter,
applyFilters : applyFilters,
addFilter : addFilter,
removeAction : removeAction,
doAction : doAction,
addAction : addAction
};
/**
* Contains the hooks that get registered with this EventManager. The array for storage utili... | ( type, hook, callback, context ) {
if ( !STORAGE[ type ][ hook ] ) {
return;
}
if ( !callback ) {
STORAGE[ type ][ hook ] = [];
} else {
var handlers = STORAGE[ type ][ hook ];
var i;
if ( !context ) {
for ( i = handlers.length; i--; ) {
if ( handlers[i].callback =... | _removeHook | identifier_name |
analytics.hooks.js | ), 10 );
_addHook( 'filters', filter, callback, priority );
}
return MethodsAvailable;
}
/**
* Performs a filter if it exists. You should only ever pass 1 argument to be filtered. The only rule is that
* the first argument must always be the filter.
*/
function applyFilters( /* fi... |
return _inbound.hooks.applyFilters.apply(this, arguments);
};
| random_line_split | |
videoscraper.py | # -*- coding: UTF-8 -*-
'''
videoscraper scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import json, urllib, urlparse
from resources.lib.modules import client
from resources.lib.modules import directstream
class source:
def __i... |
return url
| return directstream.googlepass(url) | conditional_block |
videoscraper.py | # -*- coding: UTF-8 -*-
'''
videoscraper scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import json, urllib, urlparse
from resources.lib.modules import client
from resources.lib.modules import directstream
class source:
def __i... | try:
oloads = [i['url'] for i in result if i['source'] == 'CDN']
for url in oloads:
sources.append({'source': 'CDN', 'quality': 'HD', 'language': 'en', 'url': url, 'direct': False, 'debridonly': False})
except:
pass
... | sources = []
try:
if not url:
return sources
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
url = urlparse.urljoin(self.base_link, '/sources?%s' % urllib.urlencode(data))
r = client.... | identifier_body |
videoscraper.py | # -*- coding: UTF-8 -*-
'''
videoscraper scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import json, urllib, urlparse
from resources.lib.modules import client
from resources.lib.modules import directstream
class source:
def __i... | (self, imdb, title, localtitle, aliases, year):
try:
return urllib.urlencode({'imdb': imdb, 'title': title, 'year': year})
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
return urllib.urlencode({'imdb': imd... | movie | identifier_name |
videoscraper.py | # -*- coding: UTF-8 -*-
'''
videoscraper scraper for Exodus forks.
Nov 9 2018 - Checked
Updated and refactored by someone.
Originally created by others.
'''
import json, urllib, urlparse
| class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['localhost']
self.base_link = 'http://127.0.0.1:16735'
def movie(self, imdb, title, localtitle, aliases, year):
try:
return urllib.urlencode({'imdb': imdb, 'title': ti... | from resources.lib.modules import client
from resources.lib.modules import directstream
| random_line_split |
WordCategories.js | /*
Copyright 2016 First People's Cultural Council
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... |
return categoriesDataLayerToRender
}}
</CategoriesData>
)
}
}
// REDUX: reducers/state
const mapStateToProps = (state /*, ownProps*/) => {
const { fvCategory, fvDialect, navigation } = state
const { properties } = navigation
const { computeCategories } = fvCategory
const { compu... | {
categoriesDataLayerToRender = (
<PromiseWrapper renderOnError computeEntities={computeEntities}>
<div className="row">
<div className="col-xs-12">
<CategoryList action={this._onNavigateRequest} items={categoriesData} cols={6} />
... | conditional_block |
WordCategories.js | /*
Copyright 2016 First People's Cultural Council
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | extends Component {
static propTypes = {
action: func,
routeParams: object.isRequired,
// REDUX: reducers/state
computeCategories: object.isRequired,
computeDialect2: object.isRequired,
properties: object.isRequired,
// REDUX: actions/dispatch/func
fetchPortal: func.isRequired,
pu... | WordCategories | identifier_name |
WordCategories.js | /*
Copyright 2016 First People's Cultural Council
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... |
// Fetch data on initial render
componentDidMount() {
this.fetchData(this.props)
}
// Refetch data on URL change
componentWillReceiveProps(nextProps) {
if (nextProps.routeParams.area !== this.props.routeParams.area) {
this.fetchData(nextProps)
}
}
_onNavigateRequest(category) {
i... | {
// const pathOrId = '/' + newProps.properties.domain + '/' + newProps.routeParams.area
const categoriesPath = '/api/v1/path/' + newProps.routeParams.dialect_path + '/Categories/@children'
newProps.fetchPortal(newProps.routeParams.dialect_path + '/Portal')
this.setState({ categoriesPath })
} | identifier_body |
WordCategories.js | /*
Copyright 2016 First People's Cultural Council
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | import NavigationHelpers from 'common/NavigationHelpers'
import CategoryList from 'components/CategoryList'
import PromiseWrapper from 'components/PromiseWrapper'
import CategoriesData from 'components/Categories/CategoriesData'
/**
* Categories page for words
*/
const { func, object } = PropTypes
export class Wor... | random_line_split | |
app.py | OAUTH2_CLIENT_ID = os.environ['OAUTH2_CLIENT_ID']
OAUTH2_CLIENT_SECRET = os.environ['OAUTH2_CLIENT_SECRET']
OAUTH2_REDIRECT_URI = 'http://localhost:5000/callback'
API_BASE_URL = os.environ.get('API_BASE_URL', 'https://discordapp.com/api')
AUTHORIZATION_BASE_URL = API_BASE_URL + '/oauth2/authorize'
TOKEN_URL = API_BASE... | import os
from flask import Flask, g, session, redirect, request, url_for, jsonify
from requests_oauthlib import OAuth2Session
| random_line_split | |
app.py | import os
from flask import Flask, g, session, redirect, request, url_for, jsonify
from requests_oauthlib import OAuth2Session
OAUTH2_CLIENT_ID = os.environ['OAUTH2_CLIENT_ID']
OAUTH2_CLIENT_SECRET = os.environ['OAUTH2_CLIENT_SECRET']
OAUTH2_REDIRECT_URI = 'http://localhost:5000/callback'
API_BASE_URL = os.environ.ge... |
discord = make_session(state=session.get('oauth2_state'))
token = discord.fetch_token(
TOKEN_URL,
client_secret=OAUTH2_CLIENT_SECRET,
authorization_response=request.url)
session['oauth2_token'] = token
return redirect(url_for('.me'))
@app.route('/me')
def me():
discord = m... | return request.values['error'] | conditional_block |
app.py | import os
from flask import Flask, g, session, redirect, request, url_for, jsonify
from requests_oauthlib import OAuth2Session
OAUTH2_CLIENT_ID = os.environ['OAUTH2_CLIENT_ID']
OAUTH2_CLIENT_SECRET = os.environ['OAUTH2_CLIENT_SECRET']
OAUTH2_REDIRECT_URI = 'http://localhost:5000/callback'
API_BASE_URL = os.environ.ge... |
@app.route('/me')
def me():
discord = make_session(token=session.get('oauth2_token'))
user = discord.get(API_BASE_URL + '/users/@me').json()
guilds = discord.get(API_BASE_URL + '/users/@me/guilds').json()
connections = discord.get(API_BASE_URL + '/users/@me/connections').json()
return jsonify(use... | if request.values.get('error'):
return request.values['error']
discord = make_session(state=session.get('oauth2_state'))
token = discord.fetch_token(
TOKEN_URL,
client_secret=OAUTH2_CLIENT_SECRET,
authorization_response=request.url)
session['oauth2_token'] = token
return ... | identifier_body |
app.py | import os
from flask import Flask, g, session, redirect, request, url_for, jsonify
from requests_oauthlib import OAuth2Session
OAUTH2_CLIENT_ID = os.environ['OAUTH2_CLIENT_ID']
OAUTH2_CLIENT_SECRET = os.environ['OAUTH2_CLIENT_SECRET']
OAUTH2_REDIRECT_URI = 'http://localhost:5000/callback'
API_BASE_URL = os.environ.ge... | (token=None, state=None, scope=None):
return OAuth2Session(
client_id=OAUTH2_CLIENT_ID,
token=token,
state=state,
scope=scope,
redirect_uri=OAUTH2_REDIRECT_URI,
auto_refresh_kwargs={
'client_id': OAUTH2_CLIENT_ID,
'client_secret': OAUTH2_CLIENT... | make_session | identifier_name |
gulpfile.js | (function (gulp, gulpLoadPlugins, pkg) {
'use strict';
//|**
//|
//| Gulpfile
//|
//| This file is the streaming build system
//|
//| .-------------------------------------------------------------------.
//| | NAMING CONVENTIONS: |
//| |---------------------------... | require('gulp-load-plugins'), require('./package.json')));
| rce/AM.prefix');
src.push('source/AM.suffix');
return src;
}
}(require('gulp'), | identifier_body |
gulpfile.js | (function (gulp, gulpLoadPlugins, pkg) {
'use strict';
//|**
//|
//| Gulpfile
//|
//| This file is the streaming build system
//|
//| .-------------------------------------------------------------------.
//| | NAMING CONVENTIONS: |
//| |---------------------------... | .pipe($.git.tag(version, message))
.pipe($.git.push('origin', 'master', '--tags'))
.pipe($.gulp.dest('./'));
return stream;
});
gulp.task('npm', ['tag'], function (done) {
var process = require('child_process')
.spawn('npm', ['publish'], { stdio: 'inherit' })
.on('close', done);
});
//|**~~~~~~~~~~~... | var stream = gulp.src('./')
.pipe($.git.commit(message)) | random_line_split |
gulpfile.js | (function (gulp, gulpLoadPlugins, pkg) {
'use strict';
//|**
//|
//| Gulpfile
//|
//| This file is the streaming build system
//|
//| .-------------------------------------------------------------------.
//| | NAMING CONVENTIONS: |
//| |---------------------------... | t('source/AM.prefix');
src.push('source/AM.suffix');
return src;
}
}(require('gulp'), require('gulp-load-plugins'), require('./package.json')));
| shif | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.