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 |
|---|---|---|---|---|
views.ts | import Localgroups from "./collection"
import { ensureIndex } from '../../collectionUtils';
Localgroups.addDefaultView(terms => {
let selector: any = {};
if(Array.isArray(terms.filters) && terms.filters.length) {
selector.types = {$in: terms.filters};
} else if (typeof terms.filters === "string") { //If ther... | }
return {
selector: {
...selector,
inactive: false
}
};
});
Localgroups.addView("userInactiveGroups", function (terms) {
return {
selector: {
organizerIds: terms.userId,
inactive: true
}
};
});
ensureIndex(Localgroups, { organizerIds: 1, inactive: 1 });
Localgroups.... | random_line_split | |
views.ts | import Localgroups from "./collection"
import { ensureIndex } from '../../collectionUtils';
Localgroups.addDefaultView(terms => {
let selector: any = {};
if(Array.isArray(terms.filters) && terms.filters.length) | else if (typeof terms.filters === "string") { //If there is only single value we can't distinguish between Array and value
selector.types = {$in: [terms.filters]};
}
return {
selector: {
...selector,
inactive: false
}
};
});
Localgroups.addView("userInactiveGroups", function (terms) {
... | {
selector.types = {$in: terms.filters};
} | conditional_block |
physEnt.js | fixtureDef.userData.maskBits = filterSettings.maskBits;
}
else {
fixtureDef.userData.categoryBits = this.body.GetFixtureList().GetFilterData().categoryBits;
fixtureDef.userData.maskBits = this.body.GetFixtureList().GetFilterData().maskBits;
}
fixtureDef.filter.categoryBits = ig.Filter.NOCOLLIDE;... | checkCoord.tY -= 1;
pixelCoord = tileUtil.tileToPx(checkCoord.tX, checkCoord.tY);
if (ig.game.collisionMap.getTile(pixelCoord.pX, pixelCoord.pY) != 0) { //only totally blank spaces for now
return false;
} | random_line_split | |
physEnt.js | : function(settings) {
if (typeof(settings.categoryBits) !== 'null' && typeof(settings.categoryBits) !== 'undefined') {
console.log("Category is happening");
this.categoryBits = settings.categoryBits;
}
if (typeof(settings.maskBits) !== 'null' && typeof(settings.maskBits) !== 'undefined' ) {
consol... |
},
makeSense: function(name, senseObj) {
var shapeDef = new Box2D.Collision.Shapes.b2PolygonShape();
shapeDef.SetAsOrientedBox(senseObj.size.x*Box2D.SCALE/2, senseObj.size.y*Box2D.SCALE/2, new Box2D.Common.Math.b2Vec2(senseObj.pos.x*Box2D.SCALE, senseObj.pos.y*Box2D.SCALE), 0);
var fixtureDef = new Box... | {
//PANIC
console.log("PANIC");
} | conditional_block |
mockredis.py | #!/usr/bin/env python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# mockredis
#
# This module helps start and stop redis instances for unit-testing
# redis must be pre-installed for this to work
#
import os
import signal
import subprocess
import logging
import socket
import time
import red... |
def get_redis_path():
if not os.path.exists(redis_exe):
install_redis()
return redis_exe
def redis_version():
'''
Determine redis-server version
'''
return 2.6
'''
command = "redis-server --version"
logging.info('redis_version call 1')
process = subprocess.Popen(command.sp... | if not os.path.exists(redis_url):
process = subprocess.Popen(['wget', '-P', redis_bdir,
'https://redis.googlecode.com/files/redis-'\
+ redis_ver + '.tar.gz'],
cwd=redis_bdir)
process.wait()
... | identifier_body |
mockredis.py | #!/usr/bin/env python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# mockredis
#
# This module helps start and stop redis instances for unit-testing
# redis must be pre-installed for this to work
#
import os
import signal
import subprocess
import logging
import socket
import time
import red... | (filePath, findreplace):
"replaces all findStr by repStr in file filePath"
print filePath
tempName = filePath + '~~~'
input = open(filePath)
output = open(tempName, 'w')
s = input.read()
for couple in findreplace:
outtext = s.replace(couple[0], couple[1])
s = outtext
outp... | replace_string_ | identifier_name |
mockredis.py | #!/usr/bin/env python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# mockredis
#
# This module helps start and stop redis instances for unit-testing
# redis must be pre-installed for this to work
#
import os
import signal
import subprocess
import logging
import socket
import time
import red... |
return redis_exe
def redis_version():
'''
Determine redis-server version
'''
return 2.6
'''
command = "redis-server --version"
logging.info('redis_version call 1')
process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE)
logging.info('redis_version call 2')
output... | install_redis() | conditional_block |
mockredis.py | #!/usr/bin/env python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# mockredis
#
# This module helps start and stop redis instances for unit-testing
# redis must be pre-installed for this to work
#
import os
import signal
import subprocess
import logging
import socket
import time
import red... | s = input.read()
for couple in findreplace:
outtext = s.replace(couple[0], couple[1])
s = outtext
output.write(outtext)
output.close()
input.close()
os.rename(tempName, filePath)
def call_command_(command):
process = subprocess.Popen(command.split(' '),
... | print filePath
tempName = filePath + '~~~'
input = open(filePath)
output = open(tempName, 'w') | random_line_split |
deprecated-features.js | 'use strict';
const fs = require('fs');
const path = require('path');
const ts = require('./typescript');
/**
* @param name {string}
* @param source {string}
*/
const DEPRECATED_FEATURES = (function getFeatures() {
let fileName = path.join(
__dirname,
'..',
'packages',
'@ember',
'deprecated-f... |
});
return flags;
})();
/**
* @param d {ts.VariableStatement}
* @param map {{[flag: string]: string}}
*/
function handleExportedDeclaration(d, map) {
let declaration = d.declarationList.declarations[0];
/** @type {ts.StringLiteral} */
let initializer = declaration.initializer;
if (
initializer &&
... | {
handleExportedDeclaration(statement, flags);
} | conditional_block |
deprecated-features.js | 'use strict';
const fs = require('fs');
const path = require('path');
const ts = require('./typescript');
/**
* @param name {string}
* @param source {string}
*/
const DEPRECATED_FEATURES = (function getFeatures() {
let fileName = path.join(
__dirname,
'..',
'packages',
'@ember',
'deprecated-f... | (d, map) {
let declaration = d.declarationList.declarations[0];
/** @type {ts.StringLiteral} */
let initializer = declaration.initializer;
if (
initializer &&
initializer.kind === ts.SyntaxKind.PrefixUnaryExpression &&
initializer.operand.kind === ts.SyntaxKind.PrefixUnaryExpression &&
initializ... | handleExportedDeclaration | identifier_name |
deprecated-features.js | 'use strict';
const fs = require('fs');
const path = require('path');
const ts = require('./typescript');
/**
* @param name {string}
* @param source {string}
*/
const DEPRECATED_FEATURES = (function getFeatures() {
let fileName = path.join(
__dirname,
'..',
'packages',
'@ember',
'deprecated-f... |
module.exports = DEPRECATED_FEATURES;
| {
let declaration = d.declarationList.declarations[0];
/** @type {ts.StringLiteral} */
let initializer = declaration.initializer;
if (
initializer &&
initializer.kind === ts.SyntaxKind.PrefixUnaryExpression &&
initializer.operand.kind === ts.SyntaxKind.PrefixUnaryExpression &&
initializer.operan... | identifier_body |
deprecated-features.js | 'use strict';
const fs = require('fs');
const path = require('path');
const ts = require('./typescript');
/**
* @param name {string}
* @param source {string}
*/
const DEPRECATED_FEATURES = (function getFeatures() {
let fileName = path.join(
__dirname,
'..',
'packages',
'@ember',
'deprecated-f... | if (
initializer &&
initializer.kind === ts.SyntaxKind.PrefixUnaryExpression &&
initializer.operand.kind === ts.SyntaxKind.PrefixUnaryExpression &&
initializer.operand.operand.kind === ts.SyntaxKind.StringLiteral
) {
map[declaration.name.text] = initializer.operand.operand.text;
}
}
module.ex... | random_line_split | |
handler.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | else {
outer_result
}
}
}
| {
Err(inner_result.err().or(outer_result.err()).unwrap())
} | conditional_block |
handler.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// | //
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the Licen... | // https://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
handler.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | <SD, F> {
pub(super) inner: SD,
pub(super) handler: F,
}
impl<SD, F, IC, R> SendDesc<IC, R> for Handler<SD, F>
where
SD: SendDesc<IC, ()> + Send,
IC: InboundContext,
R: Send,
F: FnMut(
Result<&dyn InboundContext<SocketAddr = IC::SocketAddr>, Error>,
) -> Result<ResponseStatu... | Handler | identifier_name |
workers.service.ts | // Copyright 2018 Google Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.... | // You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// | random_line_split |
workers.service.ts | // Copyright 2018 Google Inc
//
// 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 ... |
}
| {
return `${this.getHost()}/workers/${worker_class}/params`;
} | identifier_body |
workers.service.ts | // Copyright 2018 Google Inc
//
// 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 ... | () {
this.removeContentTypeHeader();
return this.http.get(this.url)
.toPromise()
.catch(this.handleError);
}
private getWorkerParamsUrl(worker_class) {
return `${this.getHost()}/workers/${worker_class}/params`;
}
}
| getWorkers | identifier_name |
middleware.py |
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = mongo_auth_get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), (
"The Django authent... | # coding=utf-8
from django.utils.functional import SimpleLazyObject
from mongo_auth import get_user as mongo_auth_get_user
| random_line_split | |
middleware.py | # coding=utf-8
from django.utils.functional import SimpleLazyObject
from mongo_auth import get_user as mongo_auth_get_user
def get_user(request):
if not hasattr(request, '_cached_user'):
|
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), (
"The Django authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
... | request._cached_user = mongo_auth_get_user(request) | conditional_block |
middleware.py | # coding=utf-8
from django.utils.functional import SimpleLazyObject
from mongo_auth import get_user as mongo_auth_get_user
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = mongo_auth_get_user(request)
return request._cached_user
class AuthenticationMiddleware(ob... | (self, request):
assert hasattr(request, 'session'), (
"The Django authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'django.... | process_request | identifier_name |
middleware.py | # coding=utf-8
from django.utils.functional import SimpleLazyObject
from mongo_auth import get_user as mongo_auth_get_user
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = mongo_auth_get_user(request)
return request._cached_user
class AuthenticationMiddleware(ob... | """
Formerly, a middleware for invalidating a user's sessions that don't
correspond to the user's current session authentication hash. However, it
caused the "Vary: Cookie" header on all responses.
Now a backwards compatibility shim that enables session verification in
auth.get_user() if this middl... | identifier_body | |
jqplot.categoryAxisRenderer.js | (c) 2009 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* The author would appreciate an email letting him know o... | }
else {
dim = this._plotDimensions.height;
}
// if min, max and number of ticks specified, user can't specify interval.
if (this.min != null && this.max != null && this.numberTicks != null) {
this.tickInterval = nu... | random_line_split | |
jqplot.categoryAxisRenderer.js | (c) 2009 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT and GPL version 2.0 licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* The author would appreciate an email letting him know o... |
else {
if (skip>0 && track<skip) {
t.showLabel = false;
track += 1;
}
else {
t.showLabel = true;
track = 0;
}
... | {
t.showLabel = false;
t.showMark = true;
} | conditional_block |
notify.py | from builtins import str
from builtins import object
import smtplib
import email.utils
from biomaj.workflow import Workflow
import logging
import sys
if sys.version < '3':
from email.MIMEText import MIMEText
else:
from email.mime.text import MIMEText
class Notify(object):
| if sys.version < '3':
fp = open(log_file, 'rb')
else:
fp = open(log_file, 'r')
msg = MIMEText(fp.read(2000000))
fp.close()
msg['From'] = email.utils.formataddr(('Author', mfrom))
msg['Subject'] = 'BANK[' + bank.name + '] - ... | """
Send notifications
"""
@staticmethod
def notifyBankAction(bank):
if not bank.config.get('mail.smtp.host') or bank.session is None:
logging.info('Notify:none')
return
admins = bank.config.get('mail.admin')
if not admins:
logging.info('Notif... | identifier_body |
notify.py | from builtins import str | import sys
if sys.version < '3':
from email.MIMEText import MIMEText
else:
from email.mime.text import MIMEText
class Notify(object):
"""
Send notifications
"""
@staticmethod
def notifyBankAction(bank):
if not bank.config.get('mail.smtp.host') or bank.session is None:
... | from builtins import object
import smtplib
import email.utils
from biomaj.workflow import Workflow
import logging | random_line_split |
notify.py | from builtins import str
from builtins import object
import smtplib
import email.utils
from biomaj.workflow import Workflow
import logging
import sys
if sys.version < '3':
from email.MIMEText import MIMEText
else:
from email.mime.text import MIMEText
class Notify(object):
"""
Send notifications
""... | (bank):
if not bank.config.get('mail.smtp.host') or bank.session is None:
logging.info('Notify:none')
return
admins = bank.config.get('mail.admin')
if not admins:
logging.info('Notify: no mail.admin defined')
return
admin_list = admins.spli... | notifyBankAction | identifier_name |
notify.py | from builtins import str
from builtins import object
import smtplib
import email.utils
from biomaj.workflow import Workflow
import logging
import sys
if sys.version < '3':
from email.MIMEText import MIMEText
else:
from email.mime.text import MIMEText
class Notify(object):
"""
Send notifications
""... |
server.sendmail(mfrom, [mto], msg.as_string())
except Exception as e:
logging.error('Could not send email: ' + str(e))
finally:
if server is not None:
server.quit()
| server.login(bank.config.get('mail.user'), bank.config.get('mail.password')) | conditional_block |
test_quil.py | TEST", [[1., 0.], [0., 1.]])
assert dgp.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n"
test = dgp.get_constructor()
tg = test(DirectQubit(1))
assert tg.out() == "TEST 1"
def test_instruction_group_gates():
ig = InstructionGroup()
ig.inst(H(0), X(1))
assert len(ig.actions) == 2
... |
def test_singles():
p = Program(I(0), X(0), Y(1), Z(1), H(2), T(2), S(1))
assert p.out() == 'I 0\nX 0\nY 1\nZ 1\nH 2\nT 2\nS 1\n'
def test_rotations():
p = Program(RX(0.5)(0), RY(0.1)(1), RZ(1.4)(2))
assert p.out() == 'RX(0.5) 0\nRY(0.1) 1\nRZ(1.4) 2\n'
def test_controlled_gates():
p = Progra... | p = Program().inst(X(0), Y(1), Z(0)).measure(0, 1)
assert p.out() == 'X 0\nY 1\nZ 0\nMEASURE 0 [1]\n'
p = Program().inst(X(0)).inst(Y(1)).measure(0, 1).inst(MEASURE(1, 2))
assert p.out() == 'X 0\nY 1\nMEASURE 0 [1]\nMEASURE 1 [2]\n'
p = Program().inst(X(0)).measure(0, 1).inst(Y(1), X(0)).measure(0, 0)
... | identifier_body |
test_quil.py | TEST", [[1., 0.], [0., 1.]])
assert dgp.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n"
test = dgp.get_constructor()
tg = test(DirectQubit(1))
assert tg.out() == "TEST 1"
def test_instruction_group_gates():
ig = InstructionGroup()
ig.inst(H(0), X(1))
assert len(ig.actions) == 2
... | def test_instruction_group_string():
ig = InstructionGroup()
ig.inst("Y 0",
"X 1", )
assert len(ig.actions) == 2
assert ig.out() == "Y 0\nX 1\n"
def test_program_gates():
ig = Program()
ig.inst(H(0), X(1))
assert len(ig.actions) == 2
assert ig.out() == "H 0\nX 1\n"
def te... | random_line_split | |
test_quil.py | TEST", [[1., 0.], [0., 1.]])
assert dgp.out() == "DEFGATE TEST:\n 1.0, 0.0\n 0.0, 1.0\n"
test = dgp.get_constructor()
tg = test(DirectQubit(1))
assert tg.out() == "TEST 1"
def test_instruction_group_gates():
ig = InstructionGroup()
ig.inst(H(0), X(1))
assert len(ig.actions) == 2
... | ():
p = Program().inst(HALT, WAIT, RESET, NOP)
assert p.out() == 'HALT\nWAIT\nRESET\nNOP\n'
def test_unary_classicals():
p = Program()
p.inst(TRUE(0),
FALSE(Addr(1)),
NOT(2))
assert p.out() == 'TRUE [0]\n' \
'FALSE [1]\n' \
'NOT [2]... | test_simple_instructions | identifier_name |
dissimilaroriginwindow.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::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::Dissimi... |
}
impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// https://html.spec.whatwg.org/multipage/#dom-window
fn Window(&self) -> DomRoot<WindowProxy> {
DomRoot::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-self
fn Self_(&self) -> DomRoot<Window... | {
self.upcast::<GlobalScope>().origin()
} | identifier_body |
dissimilaroriginwindow.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::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::Dissimi... | (&self) {
// TODO: Implement x-origin blur
}
// https://html.spec.whatwg.org/multipage/#dom-focus
fn Focus(&self) {
// TODO: Implement x-origin focus
}
// https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> DomRoot<DissimilarOriginLocation> {
self... | Blur | identifier_name |
dissimilaroriginwindow.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::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::Dissimi... | // https://html.spec.whatwg.org/multipage/#dom-focus
fn Focus(&self) {
// TODO: Implement x-origin focus
}
// https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> DomRoot<DissimilarOriginLocation> {
self.location.or_init(|| DissimilarOriginLocation::new(self))
... | fn Blur(&self) {
// TODO: Implement x-origin blur
}
| random_line_split |
combinations.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self):
return [test_combinations.OptionalParameter("tf_api_version")]
generate = functools.partial(
test_combinations.generate,
test_combinations=(EagerGraphCombination(), TFVersionCombination()))
combine = test_combinations.combine
times = test_combinations.times
NamedObject = test_combinations.NamedObj... | parameter_modifiers | identifier_name |
combinations.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
generate = functools.partial(
test_combinations.generate,
test_combinations=(EagerGraphCombination(), TFVersionCombination()))
combine = test_combinations.combine
times = test_combinations.times
NamedObject = test_combinations.NamedObject
tf_export("__internal__.test.combinations.generate", v1=[])(generate)... | """Control the execution of the test in TF1.x and TF2.
If TF2 is enabled then a test with TF1 test is going to be skipped and vice
versa.
Test targets continuously run in TF2 thanks to the tensorflow.v2 TAP target.
A test can be run in TF2 with bazel by passing --test_env=TF2_BEHAVIOR=1.
"""
def should_e... | identifier_body |
combinations.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def parameter_modifiers(self):
return [test_combinations.OptionalParameter("mode")]
class TFVersionCombination(test_combinations.TestCombination):
"""Control the execution of the test in TF1.x and TF2.
If TF2 is enabled then a test with TF1 test is going to be skipped and vice
versa.
Test targets co... | raise ValueError(
"Argument 'mode' must be either 'eager' or 'graph'. "
f"Received: {mode}.") | conditional_block |
combinations.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================... | # Unless required by applicable law or agreed to in writing, software | random_line_split |
BarManager.ts | import { Dragger } from '@ephox/dragster';
import { Fun, Optional } from '@ephox/katamari';
import { Bindable, Event, Events } from '@ephox/porkbun';
import { Attribute, Class, Compare, Css, DomEvent, SelectorFind, SugarBody, SugarElement } from '@ephox/sugar';
import { findClosestContentEditable, isContentEditableTrue... | adjustHeight: Event([ 'table', 'delta', 'row' ]),
adjustWidth: Event([ 'table', 'delta', 'column' ]),
startAdjust: Event([])
});
return {
destroy,
refresh,
on: resizing.on,
off: resizing.off,
hideBars: Fun.curry(Bars.hide, wire),
showBars: Fun.curry(Bars.show, wire),
events:... | const refresh = (tbl: SugarElement<HTMLTableElement>) => {
Bars.refresh(wire, tbl);
};
const events: DragAdjustEvents = Events.create({ | random_line_split |
BarManager.ts | import { Dragger } from '@ephox/dragster';
import { Fun, Optional } from '@ephox/katamari';
import { Bindable, Event, Events } from '@ephox/porkbun';
import { Attribute, Class, Compare, Css, DomEvent, SelectorFind, SugarBody, SugarElement } from '@ephox/sugar';
import { findClosestContentEditable, isContentEditableTrue... |
},
(table) => {
hoverTable = Optional.some(table);
Bars.refresh(wire, table);
}
);
});
const destroy = () => {
mousedown.unbind();
mouseover.unbind();
resizing.destroy();
Bars.destroy(wire);
};
const refresh = (tbl: SugarElement<HTMLTableElement>) => {
... | {
Bars.destroy(wire);
} | conditional_block |
testSQL.py | #!/usr/bin/env python
#
# Perform the following tests:
# 1. Generate a POT file from a set of marked SQL statements
# 2. Generate an SQL file from a translated PO file
import filecmp
import os
import subprocess
import testhelper
import unittest
class TestSQLFramework(unittest.TestCase):
basedir = os.path.dirna... |
def tearDown(self):
testhelper.tearDown(self)
def testgenpot(self):
"""
Create a POT file from our test SQL statements.
"""
subprocess.Popen(
('python', self.script, '--pot', self.sqlsource,
'--output', self.testpot),
0, None, None).... | testhelper.setUp(self) | identifier_body |
testSQL.py | #!/usr/bin/env python
#
# Perform the following tests:
# 1. Generate a POT file from a set of marked SQL statements
# 2. Generate an SQL file from a translated PO file
import filecmp
import os
import subprocess
import testhelper | script = os.path.join(basedir, '../scripts/db-seed-i18n.py')
tmpdirs = [(os.path.join(basedir, 'tmp/'))]
sqlsource = os.path.join(basedir, 'data/sqlsource.sql')
canonpot = os.path.join(basedir, 'data/sql2pot.pot')
canonpo = os.path.join(basedir, 'data/sqlsource.po')
testpot = os.path.join(basedi... | import unittest
class TestSQLFramework(unittest.TestCase):
basedir = os.path.dirname(__file__) | random_line_split |
testSQL.py | #!/usr/bin/env python
#
# Perform the following tests:
# 1. Generate a POT file from a set of marked SQL statements
# 2. Generate an SQL file from a translated PO file
import filecmp
import os
import subprocess
import testhelper
import unittest
class TestSQLFramework(unittest.TestCase):
basedir = os.path.dirna... | unittest.main() | conditional_block | |
testSQL.py | #!/usr/bin/env python
#
# Perform the following tests:
# 1. Generate a POT file from a set of marked SQL statements
# 2. Generate an SQL file from a translated PO file
import filecmp
import os
import subprocess
import testhelper
import unittest
class | (unittest.TestCase):
basedir = os.path.dirname(__file__)
script = os.path.join(basedir, '../scripts/db-seed-i18n.py')
tmpdirs = [(os.path.join(basedir, 'tmp/'))]
sqlsource = os.path.join(basedir, 'data/sqlsource.sql')
canonpot = os.path.join(basedir, 'data/sql2pot.pot')
canonpo = os.path.join(b... | TestSQLFramework | identifier_name |
widget-print.js | /* Widget: print - updated 2/7/2015 (v2.19.0) *//*
* Requires tablesorter v2.8+ and jQuery 1.2.6+
*/
/*jshint browser:true, jquery:true, unused:false */
/*global jQuery: false */
;(function($){
"use strict";
var ts = $.tablesorter,
printTable = ts.printTable = {
event : 'printTable',
basicStyle : 'table, tr... | });
})(jQuery); | remove: function(table, c){
printTable.remove(c);
}
| random_line_split |
iron-doc-mixin.d.ts | /**
* DO NOT EDIT
*
* This file was automatically generated by
* https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
*
* To modify these typings, edit the source file(s):
* iron-doc-mixin.js
*/
import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn.js';
import {html} f... |
declare global {
interface HTMLElementTagNameMap {
"iron-doc-mixin": IronDocMixinElement;
}
} | }
export {IronDocMixinElement}; | random_line_split |
makeplot.py | import matplotlib.pyplot as plt
import numpy as np
import pdb
if __name__ == "__main__":
| plt.plot(data2, color="red", label="50 clients", lw=5)
plt.plot(data3, color="orange", label="100 clients", lw=5)
plt.plot(data4, color="green", label="200 clients", lw=5)
plt.legend(loc='best', ncol=1, fontsize=18)
plt.xlabel("Time (s)", fontsize=22)
plt.ylabel("Training Error", fontsize=22)
... | fig, ax = plt.subplots(figsize=(10,5))
for clients in (10, 50, 100, 200):
median_data = np.zeros(5)
for k in (1, 2, 3, 4, 5):
data = np.loadtxt("loss_" + str(clients) + "_" + str(k) + ".csv", delimiter=',')
median_data[k-1] = data.shape[0]
print str(clients) + " ... | conditional_block |
makeplot.py | import matplotlib.pyplot as plt
import numpy as np
import pdb
if __name__ == "__main__":
fig, ax = plt.subplots(figsize=(10,5))
for clients in (10, 50, 100, 200):
median_data = np.zeros(5)
for k in (1, 2, 3, 4, 5):
data = np.loadtxt("loss_" + str(clients) + "_" + str(k) + ".csv... |
plt.legend(loc='best', ncol=1, fontsize=18)
plt.xlabel("Time (s)", fontsize=22)
plt.ylabel("Training Error", fontsize=22)
axes = plt.gca()
axes.set_ylim([0, 0.5])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.setp(ax.get_xticklabels(), fontsize=18)
... | plt.plot(data3, color="orange", label="100 clients", lw=5)
plt.plot(data4, color="green", label="200 clients", lw=5) | random_line_split |
api.rs | use std::collections::BTreeMap;
use anyhow::Result;
use lazy_static::lazy_static;
use super::WindowsEmulator;
pub enum CallingConvention {
Stdcall,
Cdecl,
}
pub struct ArgumentDescriptor {
pub ty: String,
pub name: String,
}
pub struct FunctionDescriptor {
pub calling_convention: CallingConve... |
m
};
pub static ref HOOKS: BTreeMap<String, Hook> = {
let mut m = BTreeMap::new();
m.insert(
String::from("kernel32.dll!GetVersionExA"),
Box::new(
move |emu: &mut dyn WindowsEmulator, desc: &FunctionDescriptor| -> Result<()> {
... | name: String::from("lpVersionInformation"),
}
]
}
); | random_line_split |
api.rs | use std::collections::BTreeMap;
use anyhow::Result;
use lazy_static::lazy_static;
use super::WindowsEmulator;
pub enum CallingConvention {
Stdcall,
Cdecl,
}
pub struct ArgumentDescriptor {
pub ty: String,
pub name: String,
}
pub struct | {
pub calling_convention: CallingConvention,
pub return_type: String,
pub arguments: Vec<ArgumentDescriptor>,
}
type Hook = Box<dyn Fn(&mut dyn WindowsEmulator, &FunctionDescriptor) -> Result<()> + Send + Sync>;
lazy_static! {
pub static ref API: BTreeMap<String, FunctionDescriptor> =... | FunctionDescriptor | identifier_name |
constants.py | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | DEFAULT_LOOKUP_PLUGIN_PATH = shell_expand_path(get_config(p, DEFAULTS, 'lookup_plugins', 'ANSIBLE_LOOKUP_PLUGINS', '/usr/share/ansible_plugins/lookup_plugins'))
DEFAULT_VARS_PLUGIN_PATH = shell_expand_path(get_config(p, DEFAULTS, 'vars_plugins', 'ANSIBLE_VARS_PLUGINS', '/usr/share/ansible_plugins/vars_p... | DEFAULT_CALLBACK_PLUGIN_PATH = shell_expand_path(get_config(p, DEFAULTS, 'callback_plugins', 'ANSIBLE_CALLBACK_PLUGINS', '/usr/share/ansible_plugins/callback_plugins'))
DEFAULT_CONNECTION_PLUGIN_PATH = shell_expand_path(get_config(p, DEFAULTS, 'connection_plugins', 'ANSIBLE_CONNECTION_PLUGINS', '/usr/share/ansible_... | random_line_split |
constants.py | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... |
def load_config_file():
p = ConfigParser.ConfigParser()
path1 = os.path.expanduser(os.environ.get('ANSIBLE_CONFIG', "~/.ansible.cfg"))
path2 = os.getcwd() + "/ansible.cfg"
path3 = "/etc/ansible/ansible.cfg"
if os.path.exists(path1):
p.read(path1)
elif os.path.exists(path2):
p.... | if env_var is not None:
value = os.environ.get(env_var, None)
if value is not None:
return value
if p is not None:
try:
return p.get(section, key)
except:
return default
return default | identifier_body |
constants.py | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... |
if p is not None:
try:
return p.get(section, key)
except:
return default
return default
def load_config_file():
p = ConfigParser.ConfigParser()
path1 = os.path.expanduser(os.environ.get('ANSIBLE_CONFIG', "~/.ansible.cfg"))
path2 = os.getcwd() + "/ansible.cfg... | value = os.environ.get(env_var, None)
if value is not None:
return value | conditional_block |
constants.py | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | (path):
''' shell_expand_path is needed as os.path.expanduser does not work
when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE '''
if path:
path = os.path.expanduser(path)
return path
p = load_config_file()
active_user = pwd.getpwuid(os.geteuid())[0]
# Needed so the RP... | shell_expand_path | identifier_name |
borrowck-rvalues-mutable.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) -> usize {
let v = self.value;
self.value += 1;
v
}
}
pub fn main() {
let v = Counter::new(22).get_and_inc();
assert_eq!(v, 22);
let v = Counter::new(22).inc().inc().get();
assert_eq!(v, 24);;
}
| get_and_inc | identifier_name |
borrowck-rvalues-mutable.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn get(&self) -> usize {
self.value
}
fn get_and_inc(&mut self) -> usize {
let v = self.value;
self.value += 1;
v
}
}
pub fn main() {
let v = Counter::new(22).get_and_inc();
assert_eq!(v, 22);
let v = Counter::new(22).inc().inc().get();
assert_eq!(v, ... | {
self.value += 1;
self
} | identifier_body |
borrowck-rvalues-mutable.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let v = Counter::new(22).inc().inc().get();
assert_eq!(v, 24);;
} | random_line_split | |
spark.py | (start)
D['rule2func'] = self.rule2func
D['makeSet'] = self.makeSet_fast
self.__dict__ = D
#
# A hook for GenericASTBuilder and GenericASTMatcher. Mess
# thee not with this; nor shall thee toucheth the _preprocess
# argument to addRule.
#
def preprocess(self, rule, f... |
return self.buildTree(self._START, finalitem,
tokens, len(sets)-2)
def isnullable(self, sym):
#
# For symbols in G_e only. If we weren't supporting 1.5,
# could just use sym.startswith().
#
return self._NULLABLE == sym[0:len(self._NULLABLE)]
... | if len(tokens) > 0:
self.error(tokens[i-1])
else:
self.error(None) | conditional_block |
spark.py | yet. Remedy this.
#
rv = self.makeState(state, sym)
self.edges[key] = rv
return rv
def gotoT(self, state, t):
return [self.goto(state, t)]
def gotoST(self, state, st):
rv = []
for t in self.states[state].T:
if st == t:
... | nonterminal | identifier_name | |
spark.py | ment(start)
D['rule2func'] = self.rule2func
D['makeSet'] = self.makeSet_fast
self.__dict__ = D
#
# A hook for GenericASTBuilder and GenericASTMatcher. Mess
# thee not with this; nor shall thee toucheth the _preprocess
# argument to addRule.
#
def preprocess(self, rul... | def isnullable(self, sym):
#
# For symbols in G_e only. If we weren't supporting 1.5,
# could just use sym.startswith().
#
return self._NULLABLE == sym[0:len(self._NULLABLE)]
def skip(self, (lhs, rhs), pos=0):
n = len(rhs)
while pos < n:
if... | self.error(None)
return self.buildTree(self._START, finalitem,
tokens, len(sets)-2)
| random_line_split |
spark.py | (start)
D['rule2func'] = self.rule2func
D['makeSet'] = self.makeSet_fast
self.__dict__ = D
#
# A hook for GenericASTBuilder and GenericASTMatcher. Mess
# thee not with this; nor shall thee toucheth the _preprocess
# argument to addRule.
#
def preprocess(self, rule, f... | candidate, oldrule))
candidate = 0
i = i + 1
else:
if candidate:
lhs = self._NULLABLE+lhs
rule = (lhs, rhs)
if self.newrules.has_key(lhs):
self.newrule... | worklist = []
for rulelist in self.rules.values():
for rule in rulelist:
worklist.append((rule, 0, 1, rule))
for rule, i, candidate, oldrule in worklist:
lhs, rhs = rule
n = len(rhs)
while i < n:
sym = rhs[i]
... | identifier_body |
format.rs | #[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Format(pub ChannelFormat, pub NumericFormat);
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ChannelFormat {
R4G4,
R4G4B4A4,
R5G6B5,
B5G6R5,
R5G5B5A1,
R8,
R8G8,
R8G8B8A8,
B8G8R8A8, | R11G11B10,
R10G10B10A2,
R16,
R16G16,
R16G16B16A16,
R32,
R32G32,
R32G32B32,
R32G32B32A32,
R16G8,
R32G8,
R9G9B9E5
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum NumericFormat {
UnsignedNormalizedInteger,
SignedNormalizedInteger,
UnsignedInteger,
Si... | R10G11B11, | random_line_split |
format.rs | #[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Format(pub ChannelFormat, pub NumericFormat);
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ChannelFormat {
R4G4,
R4G4B4A4,
R5G6B5,
B5G6R5,
R5G5B5A1,
R8,
R8G8,
R8G8B8A8,
B8G8R8A8,
R10G11B11,
R11G11B10,
R10G1... | {
UnsignedNormalizedInteger,
SignedNormalizedInteger,
UnsignedInteger,
SignedInteger,
Float
} | NumericFormat | identifier_name |
app.js | 'use strict';
| angular.module('myApp', [
'ngRoute',
'ngCookies',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers',
'ui.bootstrap'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/index', {templateUrl: 'partials/index.html', controller: 'IndexCtrl'});
$routeProv... | // Declare app level module which depends on filters, and services | random_line_split |
tests.py | import unittest
import asyncio
from pulsar import send
from pulsar.apps.test import test_timeout
from .manage import DiningPhilosophers
class TestPhylosophers(unittest.TestCase):
app_cfg = None
concurrency = 'thread'
@classmethod
@asyncio.coroutine
def | (cls):
app = DiningPhilosophers(name='plato',
concurrency=cls.concurrency)
cls.app_cfg = yield from send('arbiter', 'run', app)
@test_timeout(30)
@asyncio.coroutine
def test_info(self):
while True:
yield from asyncio.sleep(0.5)
... | setUpClass | identifier_name |
tests.py | import unittest
import asyncio
from pulsar import send
from pulsar.apps.test import test_timeout
from .manage import DiningPhilosophers
class TestPhylosophers(unittest.TestCase):
app_cfg = None
concurrency = 'thread'
@classmethod
@asyncio.coroutine
def setUpClass(cls):
app = DiningPhilo... | return send('arbiter', 'kill_actor', cls.app_cfg.name) | conditional_block | |
tests.py | import unittest
import asyncio
from pulsar import send
from pulsar.apps.test import test_timeout |
class TestPhylosophers(unittest.TestCase):
app_cfg = None
concurrency = 'thread'
@classmethod
@asyncio.coroutine
def setUpClass(cls):
app = DiningPhilosophers(name='plato',
concurrency=cls.concurrency)
cls.app_cfg = yield from send('arbiter', 'run'... |
from .manage import DiningPhilosophers | random_line_split |
tests.py | import unittest
import asyncio
from pulsar import send
from pulsar.apps.test import test_timeout
from .manage import DiningPhilosophers
class TestPhylosophers(unittest.TestCase):
| all.append(p)
if len(all) == 5:
break
@classmethod
def tearDownClass(cls):
if cls.app_cfg is not None:
return send('arbiter', 'kill_actor', cls.app_cfg.name)
| app_cfg = None
concurrency = 'thread'
@classmethod
@asyncio.coroutine
def setUpClass(cls):
app = DiningPhilosophers(name='plato',
concurrency=cls.concurrency)
cls.app_cfg = yield from send('arbiter', 'run', app)
@test_timeout(30)
@asyncio.corout... | identifier_body |
Utils.js | /**
* @flow
*/
import ncp from 'ncp';
export function ncpAsync(source: string, dest: string, options: any = {}) {
return new Promise((resolve, reject) => {
ncp(source, dest, options, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
export class Semaphor... | throw new Error('this.available should never be > 0 when there is someone waiting.');
} else if (this.available === 1 && this.queue.length > 0) {
// If there is someone else waiting, immediately consume the permit that was released
// at the beginning of this function and let the waiting function ... | random_line_split | |
Utils.js | /**
* @flow
*/
import ncp from 'ncp';
export function ncpAsync(source: string, dest: string, options: any = {}) |
export class Semaphore {
queue: Array<(v: boolean) => void> = [];
available = 1;
async acquire(): Promise<boolean> {
if (this.available > 0) {
this.available -= 1;
return Promise.resolve(true);
}
// If there is no permit available, we return a promise that resolves once the semaphore g... | {
return new Promise((resolve, reject) => {
ncp(source, dest, options, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
} | identifier_body |
Utils.js | /**
* @flow
*/
import ncp from 'ncp';
export function ncpAsync(source: string, dest: string, options: any = {}) {
return new Promise((resolve, reject) => {
ncp(source, dest, options, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
export class Semaphor... | (this.available > 0) {
this.available -= 1;
return Promise.resolve(true);
}
// If there is no permit available, we return a promise that resolves once the semaphore gets
// signaled enough times that "available" is equal to one.
return new Promise(resolver => this.queue.push(resolver));
... | if | identifier_name |
Utils.js | /**
* @flow
*/
import ncp from 'ncp';
export function ncpAsync(source: string, dest: string, options: any = {}) {
return new Promise((resolve, reject) => {
ncp(source, dest, options, err => {
if (err) {
reject(err);
} else |
});
});
}
export class Semaphore {
queue: Array<(v: boolean) => void> = [];
available = 1;
async acquire(): Promise<boolean> {
if (this.available > 0) {
this.available -= 1;
return Promise.resolve(true);
}
// If there is no permit available, we return a promise that resolves once... | {
resolve();
} | conditional_block |
router.d.ts |
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
pat... | OpaqueToken | identifier_name | |
router.d.ts | ` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
... |
loader?: Function;
component?: Type; | random_line_split | |
image_synthese_facette_image.py | # -*- coding: utf-8 -*-
"""
@file
@brief image et synthèse
"""
from .image_synthese_facette import Rectangle
from .image_synthese_base import Rayon, Couleur
from .image_synthese_sphere import Sphere
class R | Rectangle):
"""définit un rectangle contenant un portrait"""
def __init__(self, a, b, c, d, nom_image, pygame, invertx=False):
"""initialisation, si d == None, d est calculé comme étant
le symétrique de b par rapport au milieu du segment [ac],
la texture est une image,
si invert... | ectangleImage( | identifier_name |
image_synthese_facette_image.py | # -*- coding: utf-8 -*- | @brief image et synthèse
"""
from .image_synthese_facette import Rectangle
from .image_synthese_base import Rayon, Couleur
from .image_synthese_sphere import Sphere
class RectangleImage(Rectangle):
"""définit un rectangle contenant un portrait"""
def __init__(self, a, b, c, d, nom_image, pygame, invertx=Fal... | """
@file | random_line_split |
image_synthese_facette_image.py | # -*- coding: utf-8 -*-
"""
@file
@brief image et synthèse
"""
from .image_synthese_facette import Rectangle
from .image_synthese_base import Rayon, Couleur
from .image_synthese_sphere import Sphere
class RectangleImage(Rectangle):
"""définit un rectangle contenant un portrait"""
def __init__(self, a, b, c,... | else:
c = self.image.get_at((sx - k - 1, li))
cl = Couleur(float(c[0]) / 255, float(c[1]) / 255, float(c[2]) / 255)
return cl
class SphereReflet (Sphere):
"""implémente une sphère avec un reflet"""
def __init__(self, centre, rayon, couleur, reflet):
"""initialisation, r... | lf.image.get_at((k, li))
| conditional_block |
image_synthese_facette_image.py | # -*- coding: utf-8 -*-
"""
@file
@brief image et synthèse
"""
from .image_synthese_facette import Rectangle
from .image_synthese_base import Rayon, Couleur
from .image_synthese_sphere import Sphere
class RectangleImage(Rectangle):
"""définit un rectangle contenant un portrait"""
def __init__(self, a, b, c,... |
cla
ss SphereReflet (Sphere):
"""implémente une sphère avec un reflet"""
def __init__(self, centre, rayon, couleur, reflet):
"""initialisation, reflet est un coefficient de réflexion"""
Sphere.__init__(self, centre, rayon, couleur)
self.reflet = reflet
def __str__(self):
"... | tourne la couleur au point de coordonnée p"""
ap = p - self.a
ab = self.b - self.a
ad = self.d - self.a
abn = ab.norme2()
adn = ad.norme2()
x = ab.scalaire(ap) / abn
y = ad.scalaire(ap) / adn
sx, sy = self.image.get_size()
k, li = int(x * sx), int(... | identifier_body |
cleanup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | dbg.write_uint(stats.n_unique_boxes);
dbg.write_str("\n bytes_freed: ");
dbg.write_uint(stats.n_bytes_freed);
dbg.write_str("\n");
}
}
/// Bindings to the runtime
pub mod rustrt {
use libc::c_void;
#[link_name = "rustrt"]
pub extern {
#[rust_stack]
// F... | dbg.write_str("annihilator stats:");
dbg.write_str("\n total_boxes: ");
dbg.write_uint(stats.n_total_boxes);
dbg.write_str("\n unique_boxes: "); | random_line_split |
cleanup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
/// Bindings to the runtime
pub mod rustrt {
use libc::c_void;
#[link_name = "rustrt"]
pub extern {
#[rust_stack]
// FIXME (#4386): Unable to make following method private.
pub unsafe fn rust_get_task() -> *c_void;
}
}
| {
// We do logging here w/o allocation.
let dbg = libc::STDERR_FILENO as io::fd_t;
dbg.write_str("annihilator stats:");
dbg.write_str("\n total_boxes: ");
dbg.write_uint(stats.n_total_boxes);
dbg.write_str("\n unique_boxes: ");
dbg.write_uint(stats.n_unique_boxe... | conditional_block |
cleanup.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
use unstable::lang::local_free;
use io::WriterUtil;
use io;
use libc;
use sys;
use managed;
let mut stats = AnnihilateStats {
n_total_boxes: 0,
n_unique_boxes: 0,
n_bytes_freed: 0
};
// Pass 1: Make all boxes immortal.
for each_live_alloc |box, uniq... | annihilate | identifier_name |
quest.101.js |
//
// Speak To The Farmers ( 101 )
//
var log = require('../class.log'),
realmConfig = require('../../config.realm').config,
quest = require('../class.quest'),
questCondition = require('../class.questCondition').condition;
exports.questObject = function( args )
{
var self = this;
thi... |
quest.markCompleted({
characterId: _args.characterId,
questId: self.id,
questServer: args.questServer,
after: function(){}
});
}
});
}
... | {
return;
} | conditional_block |
quest.101.js | //
// Speak To The Farmers ( 101 )
//
var log = require('../class.log'),
realmConfig = require('../../config.realm').config,
quest = require('../class.quest'),
questCondition = require('../class.questCondition').condition;
exports.questObject = function( args )
{
var self = this;
this.co... | {
self.conditions[parameterName].checkState({
characterId: _args.characterId,
after: function()
{
conditionsCompleted++;
if( conditionsCompleted < nrConditions )
{
return;
... | this.checkConditions = function( _args )
{
var conditionsCompleted = 0;
//see if condition is met
var _callCondition = function( parameterName )
| random_line_split |
install.py | =lista[0][0]
y2=lista[0][1]
x3=lista[1][0]
y3=lista[1][1]
distancia=math.sqrt((x2-x3)**2+(y2-y3)**2)
altura=distancia/3
if y2>y3:
#print('caso1')
anguloInicial=math.asin((y2-y3)/distancia)
anguloInicialGrados=anguloInicial*180/(math.pi)
anguloGrados=180-90-anguloInicialGrados
anguloRadians=anguloGrados*... | x4=int(x3+x)
y4_0=int(y3-y)
y4=int(y4_0-altura)
poligon=[(x1,y1_0),(x2,y2),(x3,y3),(x4,y4_0)]
poligonAdd=[(x1,y1),(x2,y2),(x3,y3),(x4,y4)]
return poligon, poligonAdd
###### Get points with the mouse click######
def get_PointsSemaforZona(event,x,y,flags,param):
global frame
if event == cv2.EVENT_LBUTTONDOWN... | random_line_split | |
install.py | = | poligon=[(x1,y1_0),(x2,y2),(x3,y3),(x4,y4_0)]
poligonAdd=[(x1,y1),(x2,y2),(x3,y3),(x4,y4)]
if y3==y2:
#print('caso2')
x1=x2
y1_0=int(altura)
y1=int(2*altura)
x4=x3
y4_0=int(altura)
y4=int(2*altura)
poligon=[(x1,y1_0),(x2,y2),(x3,y3),(x4,y4_0)]
poligonAdd=[(x1,y1),(x2,y2),(x3,y3),(x4,y4)]
if y3>y... | lista[0][0]
y2=lista[0][1]
x3=lista[1][0]
y3=lista[1][1]
distancia=math.sqrt((x2-x3)**2+(y2-y3)**2)
altura=distancia/3
if y2>y3:
#print('caso1')
anguloInicial=math.asin((y2-y3)/distancia)
anguloInicialGrados=anguloInicial*180/(math.pi)
anguloGrados=180-90-anguloInicialGrados
anguloRadians=anguloGrados*(... | identifier_body |
install.py | =lista[0][0]
y2=lista[0][1]
x3=lista[1][0]
y3=lista[1][1]
distancia=math.sqrt((x2-x3)**2+(y2-y3)**2)
altura=distancia/3
if y2>y3:
#print('caso1')
anguloInicial=math.asin((y2-y3)/distancia)
anguloInicialGrados=anguloInicial*180/(math.pi)
anguloGrados=180-90-anguloInicialGrados
anguloRadians=anguloGrados*... | ################################################################3####
#
def calcPoints(imag,listaS):
imag=imag
ancho=imag.shape[1]
largo=imag.shape[0]
x1=listaS[0]
y1=listaS[1]
x=listaCorte[0][0]+(x1*ancho)//640
y=listaCorte[0][1]+(y1*largo)//480
return x, y
if __name__ == '__main__':
print (help_message)
... | taAux3.append((x,y))
if len(listaAux3)<5:
listaSemaAlta.append((Const_X*(Punto_X0+const_x_zoom*x),Const_Y*(Punto_Y0+const_y_zoom*y)))
cv2.circle(frame, (x,y),2,(0,250,255),-1)
cv2.imshow('FrameToTrafficLight',frame)
if len(listaAux3)==4:
indice_Alta=obtenerIndicesSemaforo(np.array(listaSemaAlta))
pri... | conditional_block |
install.py | =lista[0][0]
y2=lista[0][1]
x3=lista[1][0]
y3=lista[1][1]
distancia=math.sqrt((x2-x3)**2+(y2-y3)**2)
altura=distancia/3
if y2>y3:
#print('caso1')
anguloInicial=math.asin((y2-y3)/distancia)
anguloInicialGrados=anguloInicial*180/(math.pi)
anguloGrados=180-90-anguloInicialGrados
anguloRadians=anguloGrados*... | ent,x,y,flags,param):
global frame
if event == cv2.EVENT_LBUTTONDOWN:
listaAux.append((x,y))
if len(lista)>0:
listaAux1.append((x//2,y//2))
else:
listaAux1.append((x//2,y//2))
if len(listaAux)!= 0:
cv2.circle(frame, (x,y),2,(0,255,255),-1)
cv2.imshow('First_Frame',frame)
if len(listaAux)>= 2:
... | _Points(ev | identifier_name |
loader.js | import header from 'head';
class Loader {
constructor () {
// Singleton Object
if(window.CM == null){
window.CM = {};
}
window.CM.Loader = this;
let scope = this;
head.ready(document, function() {
head.load([ "/assets/css/app.css",
"/assets/js/app.js",
"/assets/js/shim.js",
... | (){
document.body.setAttribute("class", document.body.getAttribute("class").split("hideloader").join("run"));
CM.App.showPage();
let preloader = document.getElementsByClassName("preloader")[0];
if(preloader && preloader.parentNode){
preloader.parentNode.removeChild(preloader);
}
}
startApplication (){
... | removeGFX | identifier_name |
loader.js | import header from 'head';
class Loader {
constructor () {
// Singleton Object
if(window.CM == null){
window.CM = {};
}
window.CM.Loader = this;
let scope = this;
head.ready(document, function() {
head.load([ "/assets/css/app.css",
"/assets/js/app.js",
"/assets/js/shim.js",
... | } else {
CM.App.blastoff();
document.body.setAttribute("class", document.body.getAttribute("class").split("loading").join("loaded") );
setTimeout(function(){
document.body.setAttribute("class", document.body.getAttribute("class").split("loaded").join("hideloader") );
}, 500);
setTimeout(funct... | random_line_split | |
loader.js | import header from 'head';
class Loader {
constructor () {
// Singleton Object
if(window.CM == null){
window.CM = {};
}
window.CM.Loader = this;
let scope = this;
head.ready(document, function() {
head.load([ "/assets/css/app.css",
"/assets/js/app.js",
"/assets/js/shim.js",
... |
}
};
export default new Loader();
| {
CM.App.blastoff();
document.body.setAttribute("class", document.body.getAttribute("class").split("loading").join("loaded") );
setTimeout(function(){
document.body.setAttribute("class", document.body.getAttribute("class").split("loaded").join("hideloader") );
}, 500);
setTimeout(function(){ CM... | conditional_block |
loader.js | import header from 'head';
class Loader {
constructor () |
removeGFX (){
document.body.setAttribute("class", document.body.getAttribute("class").split("hideloader").join("run"));
CM.App.showPage();
let preloader = document.getElementsByClassName("preloader")[0];
if(preloader && preloader.parentNode){
preloader.parentNode.removeChild(preloader);
}
}
startAppli... | {
// Singleton Object
if(window.CM == null){
window.CM = {};
}
window.CM.Loader = this;
let scope = this;
head.ready(document, function() {
head.load([ "/assets/css/app.css",
"/assets/js/app.js",
"/assets/js/shim.js",
"//fast.fonts.com/cssapi/6536d2ad-a624-4b33-9405-4c3... | identifier_body |
sign_in_totp_code.js | /* 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/. */
const $ = require('jquery');
const _ = require('underscore');
const {assert} = require('chai');
const Account = re... | () {}
}
});
view = new View({
broker,
canGoBack: true,
metrics,
model,
notifier,
relier,
viewName: 'sign-in-totp-code',
window: windowMock
});
sinon.stub(view, 'getSignedInAccount').callsFake(() => model.get('account'));
$(windowMock.document... | captureException | identifier_name |
sign_in_totp_code.js | /* 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/. */
const $ = require('jquery');
const _ = require('underscore');
const {assert} = require('chai');
const Account = re... |
}
});
view = new View({
broker,
canGoBack: true,
metrics,
model,
notifier,
relier,
viewName: 'sign-in-totp-code',
window: windowMock
});
sinon.stub(view, 'getSignedInAccount').callsFake(() => model.get('account'));
$(windowMock.document.body)... | {} | identifier_body |
sign_in_totp_code.js | /* 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/. */
const $ = require('jquery');
const _ = require('underscore');
const {assert} = require('chai');
const Account = re... | return view.validateAndSubmit().then(assert.fail, () => {});
});
it('displays a tooltip, does not call submit', () => {
assert.isTrue(view.showValidationError.called);
assert.isFalse(view.submit.called);
});
});
const validCodes = [
TOTP_CODE,
' ' + TOTP... | random_line_split | |
Toolbar.py | # -*- coding: utf-8 -*-
# Copyright (C) 2013
# by Klemens Fritzsche, pyplane@leckstrom.de
#
# 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 program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warrant... | random_line_split | |
Toolbar.py | # -*- coding: utf-8 -*-
# Copyright (C) 2013
# by Klemens Fritzsche, pyplane@leckstrom.de
#
# 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
# ... | (self, cursor):
QtGui.QApplication.restoreOverrideCursor()
QtGui.QApplication.setOverrideCursor(QtGui.QCursor(cursord[cursor]))
if __package__ is None:
__package__ = "core.toolbar"
| set_cursor | identifier_name |
Toolbar.py | # -*- coding: utf-8 -*-
# Copyright (C) 2013
# by Klemens Fritzsche, pyplane@leckstrom.de
#
# 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
# ... | __package__ = "core.toolbar" | conditional_block | |
Toolbar.py | # -*- coding: utf-8 -*-
# Copyright (C) 2013
# by Klemens Fritzsche, pyplane@leckstrom.de
#
# 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
# ... | QtGui.QApplication.setOverrideCursor(QtGui.QCursor(cursord[cursor]))
if __package__ is None:
__package__ = "core.toolbar"
| """
This class hides the functionality of NavigationToolbar, and only
provides the necessary functions (only zooming at the moment)
"""
def _init_toolbar(self):
pass
def draw_rubberband(self, event, x0, y0, x1, y1):
height = self.canvas.figure.bbox.height
y1 = height... | identifier_body |
switch.js | import React, { Component } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { Components, registerComponent } from "@reactioncommerce/reaction-components";
class Switch extends Component {
static defaultProps = {
checked: false
}
static propTypes = {
checked... | {this.renderLabel()}
</label>
);
}
}
registerComponent("Switch", Switch);
export default Switch;
| {
const baseClassName = classnames({
rui: true,
switch: true
});
const switchControlClassName = classnames({
"switch-control": true,
"active": this.props.checked
});
return (
<label className={baseClassName}>
<input
checked={this.props.checked}
... | identifier_body |
switch.js | import React, { Component } from "react";
import PropTypes from "prop-types"; | class Switch extends Component {
static defaultProps = {
checked: false
}
static propTypes = {
checked: PropTypes.bool,
i18nKeyLabel: PropTypes.string,
i18nKeyOnLabel: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string,
onChange: PropTypes.func,
onLabel: PropTypes.s... | import classnames from "classnames";
import { Components, registerComponent } from "@reactioncommerce/reaction-components";
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.