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 |
|---|---|---|---|---|
disaster_recovery_failover.py | """Failover an inaccessible block volume to its available replicant volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
@click.command(epilog="""Failover an inaccessible... | (env, volume_id, replicant_id):
"""Failover an inaccessible block volume to its available replicant volume."""
block_storage_manager = SoftLayer.BlockStorageManager(env.client)
click.secho("""WARNING : Failover an inaccessible block volume to its available replicant volume."""
"""If a volum... | cli | identifier_name |
disaster_recovery_failover.py | """Failover an inaccessible block volume to its available replicant volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
@click.command(epilog="""Failover an inaccessible... | click.echo("Disaster Recovery Failover to replicant is now in progress.") | random_line_split | |
disaster_recovery_failover.py | """Failover an inaccessible block volume to its available replicant volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
@click.command(epilog="""Failover an inaccessible... | """Failover an inaccessible block volume to its available replicant volume."""
block_storage_manager = SoftLayer.BlockStorageManager(env.client)
click.secho("""WARNING : Failover an inaccessible block volume to its available replicant volume."""
"""If a volume (with replication) becomes inacces... | identifier_body | |
disaster_recovery_failover.py | """Failover an inaccessible block volume to its available replicant volume."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
@click.command(epilog="""Failover an inaccessible... |
block_storage_manager.disaster_recovery_failover_to_replicant(
volume_id,
replicant_id
)
click.echo("Disaster Recovery Failover to replicant is now in progress.")
| raise exceptions.CLIAbort('Aborted.') | conditional_block |
tract2council.py | import sys, os, json, time
from shapely.geometry import Polygon
# http://toblerity.org/shapely/manual.html
contains = {}
intersects = {}
dPoly = {}
unmatched = []
TRACTCOL = 'BoroCT2010' # rename this for 2000 census
def addPoly(coords):
polys = []
if (isinstance(coords[0][0], float)):
polys.append(P... | else:
intersection[dn] += p.intersection(tractPolygon).area
if (len(intersection) > 0):
for (dn, inter) in intersection.items():
iap[dn] = inter / area
return (tractNum, iap)
if __name__ == '__main__':
if (len(sys.argv) < 2):
print ... | tPoly = addPoly(tract['geometry']['coordinates'])
tractNum = tract['properties'][TRACTCOL]
intersects = set()
area = 0
intersection = {}
iap = {}
for (i) in range (0, len(tPoly)):
tractPolygon = tPoly[i]
area += tractPolygon.area
for (dn, dp) in dPoly.items():
... | identifier_body |
tract2council.py | import sys, os, json, time
from shapely.geometry import Polygon
# http://toblerity.org/shapely/manual.html
contains = {}
intersects = {}
dPoly = {}
unmatched = []
TRACTCOL = 'BoroCT2010' # rename this for 2000 census
def addPoly(coords):
polys = []
if (isinstance(coords[0][0], float)):
polys.append(P... | (tract):
tPoly = addPoly(tract['geometry']['coordinates'])
tractNum = tract['properties'][TRACTCOL]
intersects = set()
area = 0
intersection = {}
iap = {}
for (i) in range (0, len(tPoly)):
tractPolygon = tPoly[i]
area += tractPolygon.area
for (dn, dp) in dPoly.items... | inDistrict | identifier_name |
tract2council.py | import sys, os, json, time
from shapely.geometry import Polygon
# http://toblerity.org/shapely/manual.html
contains = {}
intersects = {}
dPoly = {}
unmatched = []
TRACTCOL = 'BoroCT2010' # rename this for 2000 census
def addPoly(coords):
polys = []
if (isinstance(coords[0][0], float)):
polys.append(P... | with open(intersectsFile, 'w') as intersectsfo:
json.dump(intersects, intersectsfo) | random_line_split | |
tract2council.py | import sys, os, json, time
from shapely.geometry import Polygon
# http://toblerity.org/shapely/manual.html
contains = {}
intersects = {}
dPoly = {}
unmatched = []
TRACTCOL = 'BoroCT2010' # rename this for 2000 census
def addPoly(coords):
polys = []
if (isinstance(coords[0][0], float)):
polys.append(P... |
if (len(intersection) > 0):
for (dn, inter) in intersection.items():
iap[dn] = inter / area
return (tractNum, iap)
if __name__ == '__main__':
if (len(sys.argv) < 2):
print ("Usage: tract2council.py tract.json council.json")
exit()
tractfile = sys.argv[1]
coun... | intersection[dn] += p.intersection(tractPolygon).area | conditional_block |
surface.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 std::vec;
use geom::size::Size2D;
#[deriving(Eq)]
pub enum | {
fo_rgba_8888
// TODO: RGB 565, others?
}
impl format {
fn bpp(self) -> uint {
match self {
fo_rgba_8888 => 32u
}
}
}
pub struct ImageSurface {
size: Size2D<int>,
format: format,
buffer: ~[u8]
}
impl ImageSurface {
pub fn new(size: Size2D<int>, format: f... | format | identifier_name |
surface.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 std::vec;
use geom::size::Size2D;
#[deriving(Eq)]
pub enum format {
fo_rgba_8888
// TODO: RGB 565, ot... |
}
pub struct ImageSurface {
size: Size2D<int>,
format: format,
buffer: ~[u8]
}
impl ImageSurface {
pub fn new(size: Size2D<int>, format: format) -> ImageSurface {
ImageSurface {
size: size.clone(),
format: format,
buffer: vec::from_elem((size.area() as uint... | {
match self {
fo_rgba_8888 => 32u
}
} | identifier_body |
surface.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 std::vec;
use geom::size::Size2D;
#[deriving(Eq)]
pub enum format {
fo_rgba_8888
// TODO: RGB 565, ot... |
pub struct ImageSurface {
size: Size2D<int>,
format: format,
buffer: ~[u8]
}
impl ImageSurface {
pub fn new(size: Size2D<int>, format: format) -> ImageSurface {
ImageSurface {
size: size.clone(),
format: format,
buffer: vec::from_elem((size.area() as uint) *... | }
}
} | random_line_split |
log.py | import logging
import click
from halo import Halo
DEFAULT_COLORS = {
logging.WARN: {'fg': 'yellow'},
logging.ERROR: {'fg': 'red'},
logging.CRITICAL: {'fg': 'black', 'bg': 'red'},
}
# See how Django change its logging confs with settings specifics.
# https://github.com/django/django/blob/master/django/uti... | self.halo.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
self.halo.__exit__(exc_tb, exc_val, exc_tb) | def __enter__(self): | random_line_split |
log.py | import logging
import click
from halo import Halo
DEFAULT_COLORS = {
logging.WARN: {'fg': 'yellow'},
logging.ERROR: {'fg': 'red'},
logging.CRITICAL: {'fg': 'black', 'bg': 'red'},
}
# See how Django change its logging confs with settings specifics.
# https://github.com/django/django/blob/master/django/uti... |
return super().format(record)
class Spinner:
def __init__(self, message):
self.halo = Halo(text=message, spinner='dot', color='green')
def __enter__(self):
self.halo.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
self.halo.__exit__(exc_tb, exc_val, exc_tb)
| record.msg = click.style(record.msg, **options) | conditional_block |
log.py | import logging
import click
from halo import Halo
DEFAULT_COLORS = {
logging.WARN: {'fg': 'yellow'},
logging.ERROR: {'fg': 'red'},
logging.CRITICAL: {'fg': 'black', 'bg': 'red'},
}
# See how Django change its logging confs with settings specifics.
# https://github.com/django/django/blob/master/django/uti... | self.halo.__exit__(exc_tb, exc_val, exc_tb) | identifier_body | |
log.py | import logging
import click
from halo import Halo
DEFAULT_COLORS = {
logging.WARN: {'fg': 'yellow'},
logging.ERROR: {'fg': 'red'},
logging.CRITICAL: {'fg': 'black', 'bg': 'red'},
}
# See how Django change its logging confs with settings specifics.
# https://github.com/django/django/blob/master/django/uti... | (self, exc_type, exc_val, exc_tb):
self.halo.__exit__(exc_tb, exc_val, exc_tb)
| __exit__ | identifier_name |
Template.js | /* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/docume... |
/**
* Class to process string content with placeholders into a resulting string.
* This is especially interesting to use in combination with database
* driven creation of HTML markup etc.
*/
qx.Class.define("qx.util.Template",
{
extend : qx.core.Object,
/*
*************************************************... |
************************************************************************ */ | random_line_split |
Template.js | /* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/docume... |
},
/*
---------------------------------------------------------------------------
PUBLIC API
---------------------------------------------------------------------------
*/
/**
* Returns the result string
*
* @param values {Map} Map of keys used in the template
* @... | {
delete this.run;
} | conditional_block |
__init__.py | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test.utils import override_settings
from sis_provisioner.tests import (
fdao_pws_override, fdao_hrp_override, fdao_bridge_override)
from sis_provisioner.tests.account_managers import set_uw_account
user_file_name_ov... | affiemp = set_uw_account("affiemp")
javerage = set_uw_account("javerage")
ellen = set_uw_account("ellen")
staff = set_uw_account("staff")
staff.set_disable()
retiree = set_uw_account("retiree")
tyler = set_uw_account("faculty")
leftuw = set_uw_account("leftuw")
leftuw.set_terminate... | identifier_body | |
__init__.py | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test.utils import override_settings
from sis_provisioner.tests import (
fdao_pws_override, fdao_hrp_override, fdao_bridge_override)
from sis_provisioner.tests.account_managers import set_uw_account
user_file_name_ov... | ():
affiemp = set_uw_account("affiemp")
javerage = set_uw_account("javerage")
ellen = set_uw_account("ellen")
staff = set_uw_account("staff")
staff.set_disable()
retiree = set_uw_account("retiree")
tyler = set_uw_account("faculty")
leftuw = set_uw_account("leftuw")
leftuw.set_t... | set_db_records | identifier_name |
__init__.py | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test.utils import override_settings
from sis_provisioner.tests import (
fdao_pws_override, fdao_hrp_override, fdao_bridge_override)
from sis_provisioner.tests.account_managers import set_uw_account
user_file_name_ov... |
def set_db_records():
affiemp = set_uw_account("affiemp")
javerage = set_uw_account("javerage")
ellen = set_uw_account("ellen")
staff = set_uw_account("staff")
staff.set_disable()
retiree = set_uw_account("retiree")
tyler = set_uw_account("faculty")
leftuw = set_uw_account("leftuw... | random_line_split | |
relocate.py | """Virtual environment relocatable mixin."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
class RelocateMixin(object):
"""Mixin which adds the ability to relocate a virtual environmen... |
Args:
destination (str): The target path of the virtual environment.
Note:
This does not actually move the virtual environment. Is only
rewrites the metadata required to support a move.
"""
for activate in self.bin.activates:
activate.vp... | def relocate(self, destination):
"""Configure the virtual environment for another path. | random_line_split |
relocate.py | """Virtual environment relocatable mixin."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
class RelocateMixin(object):
"""Mixin which adds the ability to relocate a virtual environmen... | "python" in shebang[0] or "pypy" in shebang[0]
):
binfile.shebang = "#!{0}".format(
os.path.join(destination, "bin", "python")
)
elif len(shebang) == 3 and (
"python" in shebang[1] or ... | """Configure the virtual environment for another path.
Args:
destination (str): The target path of the virtual environment.
Note:
This does not actually move the virtual environment. Is only
rewrites the metadata required to support a move.
"""
for a... | identifier_body |
relocate.py | """Virtual environment relocatable mixin."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
class RelocateMixin(object):
"""Mixin which adds the ability to relocate a virtual environmen... | (self, destination):
"""Reconfigure and move the virtual environment to another path.
Args:
destination (str): The target path of the virtual environment.
Note:
Unlike `relocate`, this method *will* move the virtual to the
given path.
"""
sel... | move | identifier_name |
relocate.py | """Virtual environment relocatable mixin."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
class RelocateMixin(object):
"""Mixin which adds the ability to relocate a virtual environmen... |
def move(self, destination):
"""Reconfigure and move the virtual environment to another path.
Args:
destination (str): The target path of the virtual environment.
Note:
Unlike `relocate`, this method *will* move the virtual to the
given path.
"... | if file_.abspath.endswith(".pth"):
content = ""
with open(file_.abspath, "r") as source:
# .pth files are almost always very small. Because of
# this we read the whole file as a convenience.
content = source.... | conditional_block |
socket_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import socket
import select
import json
import morse.core.middleware
from functools import partial
from morse.core import services
class MorseSocketServ:
def __init__(self, port, component_name):
# List of socket clients
self._client_s... |
def print_open_sockets(self):
""" Display a list of all currently opened sockets."""
logger.info("Socket Mid: Currently opened sockets:")
for name, socket in self._socket_dict.iteritems():
logger.info(" - Port name '{0}' = '{1}'".format(name, socket))
| return json.loads(msg.decode('utf-8')) | identifier_body |
socket_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import socket
import select
import json
import morse.core.middleware
from functools import partial
from morse.core import services
class MorseSocketServ:
def __init__(self, port, component_name):
# List of socket clients
self._client_s... | (self, component_instance):
return (json.dumps(component_instance.local_data) + '\n').encode()
def read_message(self, msg):
return json.loads(msg.decode('utf-8'))
def print_open_sockets(self):
""" Display a list of all currently opened sockets."""
logger.info("Socket Mid: Curre... | post_message | identifier_name |
socket_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import socket
import select
import json
import morse.core.middleware
from functools import partial
from morse.core import services
class MorseSocketServ:
def __init__(self, port, component_name):
# List of socket clients
self._client_s... | serv = MorseSocketServ(self._base_port, component_name)
self._server_dict[self._base_port] = serv
self._component_nameservice[component_name] = self._base_port
self._base_port = self._base_port + 1
# Extract the information for this middleware
# This will be tailored for... | # Create a socket server for this component | random_line_split |
socket_mw.py | import logging; logger = logging.getLogger("morse." + __name__)
import socket
import select
import json
import morse.core.middleware
from functools import partial
from morse.core import services
class MorseSocketServ:
def __init__(self, port, component_name):
# List of socket clients
self._client_s... |
self._client_sockets.append(sock)
else:
try:
msg = i.recv(self._message_size)
logger.debug("received msg %s" % msg)
if msg == b'':
self.close_socket(i)
else:
... | logger.warning("More than one clients for an actuator!!") | conditional_block |
flap_limits.py | # Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
def _RudderFlapToServo(flap_angle):
servo_config = _CONFIG['system']['servos'][system_types.kServoR1]
return math.asin(flap_angle / servo_config['nonlinear_servo_to_flap_ratio'])
def FlapsToServos(flaps):
"""Convert flap limits to servo limits."""
servos = {}
for flap, flap_range in flaps.iteritems():
... | servo_config = _CONFIG['system']['servos'][system_types.kServoR1]
return servo_config['nonlinear_servo_to_flap_ratio'] * math.sin(servo_angle) | identifier_body |
flap_limits.py | # Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | _SERVOS = ['A' + f for f in '124578'] + ['E1', 'E2', 'R1', 'R2']
_FLAPS = _SERVOS[0:6] + ['Elevator', 'Rudder']
def GetSimLimits():
servo_limits = [_CONFIG['sim']['servos_sim'][i]['servo_drive']
for i in range(len(_SERVOS))]
return {_SERVOS[i]: (servo_limits[i]['ref_model_min_position_limit'],
... | from makani.control import system_types
_CONFIG = mconfig.MakeParams('common.all_params') | random_line_split |
flap_limits.py | # Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
elif flap == 'Elevator':
servos['E1'] = flap_range
servos['E2'] = flap_range
elif flap == 'Rudder':
servos['R1'] = (_RudderFlapToServo(flap_range[0]),
_RudderFlapToServo(flap_range[1]))
servos['R2'] = servos['R1']
else:
raise ValueError('Invalid flap %s' ... | servos[flap] = flap_range | conditional_block |
flap_limits.py | # Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | ():
return _GetControlOutputLimits(_CONFIG['control']['trans_in']['output'])
def GetControlHoverLimits():
return _GetControlOutputLimits(_CONFIG['control']['hover']['output'])
def GetControlManualLimits():
return _GetControlOutputLimits(_CONFIG['control']['manual']['output'])
def GetAvionicsServoLimits():
... | GetControlTransInLimits | identifier_name |
svm.py | sample point have a lagrange factor
self.alpha = numpy.array([0.0 for i in range(self.SampleNum)])
# The expected weight vector which we want the machine to learn
self.W = numpy.array([0.0 for i in range(self.SampleDem)])
# intercept
self.b = 0.0
# Dif... | (self, i, j):
summer = 0.0
for d in range(self.SampleDem):
summer += self._Mat[d][i] * self._Mat[d][j]
return summer
"""
Current output for sample point @i
"""
def G(self, i):
summer = 0.0
for j in range(self.SampleNum):
summer += self.al... | Linear_Kernel | identifier_name |
svm.py | sample point have a lagrange factor
self.alpha = numpy.array([0.0 for i in range(self.SampleNum)])
# The expected weight vector which we want the machine to learn
self.W = numpy.array([0.0 for i in range(self.SampleDem)])
# intercept
self.b = 0.0
# Dif... |
new_E_P1 = summer + self.b - self._Tag[P1]
summer = 0.0
for j in range(self.SampleNum):
if self.SupVec[j] == True:
summer += self.alpha[j] * self._Tag[j] * self.Kernel(P2, j)
new_E_P2 = summer + self.b - self._Tag[P2]
self.E[P1] = new_E_P1
... | summer += self.alpha[j] * self._Tag[j] * self.Kernel(P1, j) | conditional_block |
svm.py | .W = numpy.array([0.0 for i in range(self.SampleDem)])
# intercept
self.b = 0.0
# Difference between the expected output and output of current machine
self.E = numpy.array([0.0 for i in range(self.SampleNum)])
self.Kernel = self.Linear_Kernel
# Bool value ... | times = 0
while self.run_or_not():
times += 1
print "Training time:", times
if times == self.MAXITER:
break
P1 = self.findFirstVar()
P2 = self.findSecondVar(P1)
self.P1 = P1
self.P2 = P2
self.opti... | identifier_body | |
svm.py | Each sample point have a lagrange factor
self.alpha = numpy.array([0.0 for i in range(self.SampleNum)])
# The expected weight vector which we want the machine to learn
self.W = numpy.array([0.0 for i in range(self.SampleDem)])
# intercept
self.b = 0.0
... |
return firstPointIndex
"""
Find the second variable which's alpha value want to be updated
"""
def findSecondVar(self, firstPointIndex):
secondPointIndex = None
val = 0
if self.E[firstPointIndex] < 0:
maxVal = self.E[firstPointIndex]
for i in ra... | random_line_split | |
job.js | * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.or... | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with | random_line_split | |
job.js | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "Lice... | (){
if (this.get('fromBundleId')) {
this.controller.set('fromBundleId', this.get('fromBundleId'));
}
if (this.get('fromCoordId')) {
this.controller.set('fromCoordId',this.get('fromCoordId'));
}
},
onTabChange : function(tab){
this.set('currentTab', tab);
this... | didTransition | identifier_name |
job.js | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "Lice... |
if (this.get('fromCoordId')) {
this.controller.set('fromCoordId',this.get('fromCoordId'));
}
},
onTabChange : function(tab){
this.set('currentTab', tab);
this.controller.set('currentTab',tab);
},
backToSearch : function(){
var params = this.get('history').getSearch... | {
this.controller.set('fromBundleId', this.get('fromBundleId'));
} | conditional_block |
job.js | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "Lice... | ,
model : function(params){
return this.getJobInfo(Ember.ENV.API_URL+'/v2/job/'+params.id+'?show=info&timezone=GMT&offset=1&len='+Ember.ENV.PAGE_SIZE).catch(function(){
return {error : "Remote API Failed"};
}).then(function(response){
if (typeof response === "string") {
response = JS... | {
var deferred = Ember.RSVP.defer();
Ember.$.get(url).done(function(res){
deferred.resolve(res);
}).fail(function(){
deferred.reject();
});
return deferred.promise;
} | identifier_body |
decorators.py | import sys
import inspect
from functools import partial
__all__ = ['decorator', 'wraps', 'unwrap', 'ContextDecorator', 'contextmanager']
def decorator(deco):
# Any arguments after first become decorator arguments
has_args = get_argcounts(deco) != (1, False, False)
if has_args:
# A decorator wit... |
_cache[func] = get_arg
return get_arg
### Backport python 3.4 contextlib utilities
### namely ContextDecorator and contextmanager (also producing decorator)
if sys.version_info >= (3, 4):
from contextlib import ContextDecorator, contextmanager
else:
class ContextDecorator(object):
"A base c... | if name not in argnames:
raise TypeError("%s() doesn't have argument named %s" % (func.__name__, name))
else:
if name in kwargs:
return kwargs[name]
elif name in argnames:
index = argnames.index(name)
if index < len(args):
... | identifier_body |
decorators.py | import sys
import inspect
from functools import partial
__all__ = ['decorator', 'wraps', 'unwrap', 'ContextDecorator', 'contextmanager']
def decorator(deco):
# Any arguments after first become decorator arguments
has_args = get_argcounts(deco) != (1, False, False)
if has_args:
# A decorator wit... |
else:
return self._func(*(self._args + a), **dict(self._kwargs, **kw))
def __getattr__(self, name):
try:
res = self.__dict__[name] = arggetter(self._func)(name, self._args, self._kwargs)
return res
except TypeError as e:
raise AttributeError(... | return self._func(*self._args, **self._kwargs) | conditional_block |
decorators.py | import sys
import inspect
from functools import partial
__all__ = ['decorator', 'wraps', 'unwrap', 'ContextDecorator', 'contextmanager']
def decorator(deco):
# Any arguments after first become decorator arguments
has_args = get_argcounts(deco) != (1, False, False)
if has_args:
# A decorator wit... | class ContextDecorator(object):
"A base class or mixin that enables context managers to work as decorators."
def _recreate_cm(self):
"""Return a recreated instance of self.
Allows an otherwise one-shot context manager like
_GeneratorContextManager to support use... | if sys.version_info >= (3, 4):
from contextlib import ContextDecorator, contextmanager
else: | random_line_split |
decorators.py | import sys
import inspect
from functools import partial
__all__ = ['decorator', 'wraps', 'unwrap', 'ContextDecorator', 'contextmanager']
def decorator(deco):
# Any arguments after first become decorator arguments
has_args = get_argcounts(deco) != (1, False, False)
if has_args:
# A decorator wit... | (ContextDecorator):
"""Helper for @contextmanager decorator."""
def __init__(self, func, *args, **kwds):
self.gen = func(*args, **kwds)
self.func, self.args, self.kwds = func, args, kwds
# Issue 19330: ensure context manager instances have good docstrings
... | _GeneratorContextManager | identifier_name |
slidefx.js | /* Zepto plugin : slide transition v1.1 */
(function($) {
/* SlideDown */
$.fn.slideDown = function(duration, callback) {
// get the element position to restore it then
var position = this.css('position');
// show element if it is hidden
this.show();
// place it so it displays as usually but hidden
th... | marginBottom: marginBottom,
paddingTop: paddingTop,
paddingBottom: paddingBottom
});
// animate element height, margin and padding to zero
target.animate({
height: 0,
marginTop: 0,
marginBottom: 0,
paddingTop: 0,
paddingBottom: 0
}, {
// callback : restore the element po... | {
var target = this;
// get the element position to restore it then
var position = target.css('position');
// get the element height, margin and padding to restore them then
var height = target.css('height');
var marginTop = target.css('margin-top');
var marginBottom = target.css('margin-bottom'... | conditional_block |
slidefx.js | /* Zepto plugin : slide transition v1.1 */
(function($) {
/* SlideDown */
$.fn.slideDown = function(duration, callback) {
// get the element position to restore it then
var position = this.css('position');
// show element if it is hidden
this.show();
// place it so it displays as usually but hidden
th... | });
}
return this;
};
/* SlideToggle */
$.fn.slideToggle = function(duration, callback) {
// if the element is hidden, slideDown !
if (this.height() == 0) {
this.slideDown(duration, callback);
}
// if the element is visible, slideUp !
else {
this.slideUp(duration, callback);
}
return thi... | paddingBottom: paddingBottom
});
callback && callback();
} | random_line_split |
15.2.3.7-6-a-12.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... |
runTestCase(testcase);
| {
var fun = function () { };
Object.defineProperty(fun, "prop", {
value: 11,
configurable: false
});
try {
Object.defineProperties(fun, {
prop: {
value: 12,
configurable: true
}
... | identifier_body |
15.2.3.7-6-a-12.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... |
function testcase() {
var fun = function () { };
Object.defineProperty(fun, "prop", {
value: 11,
configurable: false
});
try {
Object.defineProperties(fun, {
prop: {
value: 12,
configurable: tr... | random_line_split | |
15.2.3.7-6-a-12.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... | () {
var fun = function () { };
Object.defineProperty(fun, "prop", {
value: 11,
configurable: false
});
try {
Object.defineProperties(fun, {
prop: {
value: 12,
configurable: true
... | testcase | identifier_name |
index.js | 'use strict';
var path = require('path')
, _ = require('lodash')
, chalk = require('chalk')
, yo = require('yeoman-generator')
, utils = require('../lib/utils')
, Base = yo.generators.Base;
_.mixin(require('lodash-deep'));
var AppGenerator = Base.extend({
constructor: function () {
Base.appl... | , name: 'type'
, message: 'What kind of addon is this?'
, default: this.config.get('type')
, choices: ['Application', 'Plugin', 'Theme']
}, {
type: 'input'
, name: 'name'
, message: 'Enter the name of your addon'
, default: _.deepGetValue(this, 'addon.name')
... |
askForAddon: function () {
var next = this.async()
, prompts = [{
type: 'list' | random_line_split |
index.js | 'use strict';
var path = require('path')
, _ = require('lodash')
, chalk = require('chalk')
, yo = require('yeoman-generator')
, utils = require('../lib/utils')
, Base = yo.generators.Base;
_.mixin(require('lodash-deep'));
var AppGenerator = Base.extend({
constructor: function () {
Base.appl... | else {
this.license = 'Proprietary';
}
this.template('README.md');
/* istanbul ignore next */
var extra = function (template, dest) {
if (self.extras.indexOf(template) !== -1) {
self.template(template, dest);
}
};
switch (this.type) {
case 'Application':
t... | {
this.template('licenses/' + this.license + '.md', 'LICENSE.md');
} | conditional_block |
configuration_server.py | import zmq
import sys
import ConfigParser
import os.path
import proto_objs.venue_configuration_pb2
import daemon
import signal
import lockfile
from optparse import OptionParser
import datetime
full_config = proto_objs.venue_configuration_pb2.configuration()
bind_addr="tcp://127.0.0.1:11111"
def parse(filename):
... |
def run(config_filename):
# Create context and connect
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.setsockopt(zmq.LINGER, 0)
print "Binding to: ", bind_addr
socket.bind(bind_addr)
while True:
contents = socket.recv()
print datetime.datetime.no... | single_venue_config.venue_id = config.getint(section, 'venue_id')
single_venue_config.mic_name = config.get(section, 'mic_name')
single_venue_config.order_interface_addr = config.get(section, 'order_interface_addr')
single_venue_config.order_ping_addr = config.get(section, 'order_ping_addr')
single_venu... | identifier_body |
configuration_server.py | import zmq
import sys
import ConfigParser
import os.path
import proto_objs.venue_configuration_pb2
import daemon
import signal
import lockfile
from optparse import OptionParser
import datetime |
full_config = proto_objs.venue_configuration_pb2.configuration()
bind_addr="tcp://127.0.0.1:11111"
def parse(filename):
config = ConfigParser.ConfigParser()
config.read(filename)
sections = config.sections()
full_config.Clear()
i = 0
for s in sections:
if s == 'global':
... | random_line_split | |
configuration_server.py | import zmq
import sys
import ConfigParser
import os.path
import proto_objs.venue_configuration_pb2
import daemon
import signal
import lockfile
from optparse import OptionParser
import datetime
full_config = proto_objs.venue_configuration_pb2.configuration()
bind_addr="tcp://127.0.0.1:11111"
def parse(filename):
... |
def terminate():
print "Terminate"
socket.close()
context.close()
def main():
parser = OptionParser(usage="usage: %prog [options] <config_filename>")
parser.add_option("-D", "--daemon",
dest="runAsDaemon",
help="Run configuration server as daemon",
actio... | contents = socket.recv()
print datetime.datetime.now(), "Received msg:<", contents, ">"
if contents == 'R':
print "Refresh request"
refresh_ret = parse(config_filename)
if (refresh_ret == True):
refresh_status = "OK"
else:
... | conditional_block |
configuration_server.py | import zmq
import sys
import ConfigParser
import os.path
import proto_objs.venue_configuration_pb2
import daemon
import signal
import lockfile
from optparse import OptionParser
import datetime
full_config = proto_objs.venue_configuration_pb2.configuration()
bind_addr="tcp://127.0.0.1:11111"
def | (filename):
config = ConfigParser.ConfigParser()
config.read(filename)
sections = config.sections()
full_config.Clear()
i = 0
for s in sections:
if s == 'global':
full_config.trade_serialization_addr = config.get(s, 'trade_serialization_addr')
full_config.rec... | parse | identifier_name |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... |
/// Publish data for a topic
pub fn publish(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let topic = cx.argument::<JsString>(0)?.value(&mut cx);
let json = cx.argument::<JsString>(1)?.value(&mut cx);
bridging_subscriber(topic, from_json::<serde_json::Value>(&mut cx, &json)?);
Ok(cx.undefined(... | {
let topic = cx.argument::<JsString>(0)?.value(&mut cx);
let mut subscriptions = obtain(&mut cx)?;
subscriptions.retain(|subscription| subscription.topic != topic);
Ok(cx.undefined())
} | identifier_body |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... | "While attempting to initialize pubsub: {}",
error.to_string()
));
}
Ok(cx.undefined())
} | random_line_split | |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... | (cx: &mut FunctionContext) -> NeonResult<MutexGuard<'static, Vec<JsSubscription>>> {
match SUBSCRIPTIONS.try_lock() {
Ok(guard) => Ok(guard),
Err(error) => cx.throw_error(format!(
"When attempting to obtain subscriptions: {}",
error.to_string()
)),
}
}
/// Subscr... | obtain | identifier_name |
pubsub.rs | use crate::prelude::from_json;
use neon::prelude::*;
use std::sync::{Mutex, MutexGuard};
use stencila::{
once_cell::sync::{Lazy, OnceCell},
serde_json,
};
/// The Neon event queue to which published events will be sent
static CHANNEL: OnceCell<Channel> = OnceCell::new();
/// A JavaScript subscription
#[derive... |
}
Ok(())
});
}
}
/// Initialize the pubsub module by registering the `bridging_subscriber`
/// as a subscriber to all topics.
pub fn init(mut cx: FunctionContext) -> JsResult<JsUndefined> {
if let Err(error) = events::subscribe("*", events::Subscriber::Function(bridging_subscri... | {
let callback = subscriber.to_inner(&mut cx);
let this = cx.undefined();
let json = serde_json::to_string(&data).expect("Unable to convert to JSON");
let args = vec![cx.string(&topic), cx.string(json)];
callback.call(&m... | conditional_block |
interaction.ts | import { DateComponent } from '../component/DateComponent'
export abstract class Interaction {
component: DateComponent<any>
constructor(settings: InteractionSettings) {
this.component = settings.component
}
destroy() {
}
}
export type InteractionClass = { new(settings: InteractionSettings): Interacti... |
export function interactionSettingsToStore(settings: InteractionSettings) {
return {
[settings.component.uid]: settings,
}
}
// global state
export const interactionSettingsStore: InteractionSettingsStore = {}
| {
return {
component,
el: input.el,
useEventCenter: input.useEventCenter != null ? input.useEventCenter : true,
}
} | identifier_body |
interaction.ts | import { DateComponent } from '../component/DateComponent'
export abstract class Interaction {
component: DateComponent<any>
constructor(settings: InteractionSettings) {
this.component = settings.component
}
destroy() {
}
}
export type InteractionClass = { new(settings: InteractionSettings): Interacti... | (component: DateComponent<any>, input: InteractionSettingsInput): InteractionSettings {
return {
component,
el: input.el,
useEventCenter: input.useEventCenter != null ? input.useEventCenter : true,
}
}
export function interactionSettingsToStore(settings: InteractionSettings) {
return {
[settings.... | parseInteractionSettings | identifier_name |
interaction.ts | import { DateComponent } from '../component/DateComponent'
export abstract class Interaction {
component: DateComponent<any>
constructor(settings: InteractionSettings) {
this.component = settings.component
}
destroy() {
}
}
export type InteractionClass = { new(settings: InteractionSettings): Interacti... | return {
[settings.component.uid]: settings,
}
}
// global state
export const interactionSettingsStore: InteractionSettingsStore = {} | random_line_split | |
taskDefinitions.tsx | import React from "react";
import {Col, Button} from "helpers/reactstrap";
import "./style.scss";
import DefinitionList from "./definitionList";
import {
useTaskTemplatesSubscription,
useTaskDefinitionsQuery,
useImportTemplatesMutation,
TaskDefinitionsDocument,
} from "generated/graphql";
import {Outlet} from "... | window.location.reload();
});
}
}}
/>
</label>
</Col>
<Outlet />
</React.Fragment>
);
};
export default TaskDefinitions; | fetch(`/importTaskTemplates`, {
method: "POST",
body: data,
}).then(() => { | random_line_split |
test_text_to_speech.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | (self, mock_client, mock_get_creds, mock_client_info):
result = self.gcp_text_to_speech_hook.get_conn()
mock_client.assert_called_once_with(
credentials=mock_get_creds.return_value,
client_info=mock_client_info.return_value
)
self.assertEqual(mock_client.return_va... | test_text_to_speech_client_creation | identifier_name |
test_text_to_speech.py | # regarding copyright ownership. The ASF licenses this file
# to you 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 la... | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information | random_line_split | |
test_text_to_speech.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
@patch("airflow.gcp.hooks.text_to_speech.CloudTextToSpeechHook.client_info", new_callable=PropertyMock)
@patch("airflow.gcp.hooks.text_to_speech.CloudTextToSpeechHook._get_credentials")
@patch("airflow.gcp.hooks.text_to_speech.TextToSpeechClient")
def test_text_to_speech_client_creation(self, mock_cli... | with patch(
"airflow.gcp.hooks.base.CloudBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.gcp_text_to_speech_hook = CloudTextToSpeechHook(gcp_conn_id="test") | identifier_body |
journal-editor-styles.js | /*
Defines the default styles available in the CKEditor used for the
submission of journal articles. These styles should be in sync with
the CSS styles and the HTML templates of the journal
See config.stylesSet in the configuration file.
*/
CKEDITOR.stylesSet.add( 'journal-editor-style',
[
// Inl... | { name : 'Image With Caption on Left', element : 'table', attributes : { 'class' : 'phl'} },
{ name : 'Image With Caption on Right', element : 'table', attributes : { 'class' : 'phr'} },
{ name : 'Centered Image With Caption', element : 'table', attributes : { 'class' : 'ph'} }
]); | // Object styles
{ name : 'Image on Left', element : 'img', attributes : { 'class' : 'phl' } },
{ name : 'Image on Right', element : 'img', attributes : { 'class' : 'phr'} },
{ name : 'Centered Image', element : 'img', attributes : { 'class' : 'ph'} }, | random_line_split |
browser_util.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { NgZone } from '@angular/core';
export declare let browserDetection: BrowserDetection;
export declare class | {
private _overrideUa;
private _ua;
static setup(): void;
constructor(ua: string);
isFirefox: boolean;
isAndroid: boolean;
isEdge: boolean;
isIE: boolean;
isWebkit: boolean;
isIOS7: boolean;
isSlow: boolean;
supportsNativeIntlApi: boolean;
isChromeDesktop: boolean;
... | BrowserDetection | identifier_name |
browser_util.d.ts | /**
* @license | */
import { NgZone } from '@angular/core';
export declare let browserDetection: BrowserDetection;
export declare class BrowserDetection {
private _overrideUa;
private _ua;
static setup(): void;
constructor(ua: string);
isFirefox: boolean;
isAndroid: boolean;
isEdge: boolean;
isIE: boole... | * Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license | random_line_split |
2d.shadow.pattern.transparent.2.worker.js | // DO NOT EDIT! This test has been generated by tools/gentest.py.
// OffscreenCanvas test in a worker:2d.shadow.pattern.transparent.2
// Description:Shadows are not drawn for transparent parts of fill patterns
// Note:
importScripts("/resources/testharness.js");
importScripts("/2dcontext/resources/canvas-tests.js");
... |
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
var promise = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("GET", '/images/redtransparent.png');
xhr.responseType = 'blob';
xhr.send();
xhr.onload = function() {
... | var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
throw reason;
});
t.step(function() { | random_line_split |
locale_nb.ts | //
// Copyright 2020-21 Volker Sorge
//
// 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 agree... |
/**
* @returns The Bokmal Locale.
*/
function create(): Locale {
const loc = createLocale();
loc.NUMBERS = NUMBERS;
loc.ALPHABETS.combiner = tr.Combiners.prefixCombiner;
loc.ALPHABETS.digitTrans.default = NUMBERS.numberToWords;
loc.FUNCTIONS.radicalNestDepth = nestingToString;
return loc;
}
| {
if (!locale) {
locale = create();
}
// TODO: Initialise the grammar methods here?
return locale;
} | identifier_body |
locale_nb.ts | //
// Copyright 2020-21 Volker Sorge
//
// 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 agree... | (): Locale {
const loc = createLocale();
loc.NUMBERS = NUMBERS;
loc.ALPHABETS.combiner = tr.Combiners.prefixCombiner;
loc.ALPHABETS.digitTrans.default = NUMBERS.numberToWords;
loc.FUNCTIONS.radicalNestDepth = nestingToString;
return loc;
}
| create | identifier_name |
locale_nb.ts | //
// Copyright 2020-21 Volker Sorge
//
// 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 agree... | */
export function nb(): Locale {
if (!locale) {
locale = create();
}
// TODO: Initialise the grammar methods here?
return locale;
}
/**
* @returns The Bokmal Locale.
*/
function create(): Locale {
const loc = createLocale();
loc.NUMBERS = NUMBERS;
loc.ALPHABETS.combiner = tr.Combiners.prefixCombi... |
/**
* @returns The Bokmal Locale. | random_line_split |
locale_nb.ts | //
// Copyright 2020-21 Volker Sorge
//
// 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 agree... |
// TODO: Initialise the grammar methods here?
return locale;
}
/**
* @returns The Bokmal Locale.
*/
function create(): Locale {
const loc = createLocale();
loc.NUMBERS = NUMBERS;
loc.ALPHABETS.combiner = tr.Combiners.prefixCombiner;
loc.ALPHABETS.digitTrans.default = NUMBERS.numberToWords;
loc.FUNCTIO... | {
locale = create();
} | conditional_block |
respond.src.js | ";
fakeBody.appendChild(div);
return function(q) {
div.innerHTML = '­<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth === 42;
docElem.removeChild(fakeBody);
return {
matches: bool,
me... | callMedia | identifier_name | |
respond.src.js | function(q) {
div.innerHTML = '­<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth === 42;
docElem.removeChild(fakeBody);
return {
matches: bool,
media: q
};
};
}(w.document);
})(t... | {
applyMedia(true);
} | identifier_body | |
respond.src.js | .innerHTML = '­<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth === 42;
docElem.removeChild(fakeBody);
return {
matches: bool,
media: q
};
};
}(w.document);
})(this);
(function(w) {
... | if (w.addEventListener) { | random_line_split | |
respond.src.js | .firstChild, fakeBody = doc.createElement("body"), div = doc.createElement("div");
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q) {
div.innerHTML = '­<style media="' + q + '"> #mq-t... |
if (useMedia) {
ql = 1;
}
for (var i = 0; i < ql; i++) {
var fullq, thisq, eachq, eql;
if (useMedia) {
fullq = media;
rules.push(repUrls(styles));
} else {
fullq = qs[i].match(respond.regex.findStyles) && RegExp.$1;
rules.push(RegExp.$2 && repUrls(Reg... | {
href += "/";
} | conditional_block |
index.ts | import global, { describe } from 'global';
import addons, { mockChannel } from '@storybook/addons';
import ensureOptionsDefaults from './ensureOptionsDefaults';
import snapshotsTests from './snapshotsTestsTemplate';
import integrityTest from './integrityTestTemplate';
import loadFramework from '../frameworks/frameworkL... | const { kind, storyFn: render, parameters } = item;
const existing = acc.find((i: any) => i.kind === kind);
const { fileName } = item.parameters;
if (!isDisabled(parameters.storyshots)) {
if (existing) {
existing.children.push({ ...item, render, fileName });
... | .filter(({ kind }) => (storyKindRegex ? kind.match(storyKindRegex) : true))
.reduce(
(acc, item) => { | random_line_split |
index.ts | import global, { describe } from 'global';
import addons, { mockChannel } from '@storybook/addons';
import ensureOptionsDefaults from './ensureOptionsDefaults';
import snapshotsTests from './snapshotsTestsTemplate';
import integrityTest from './integrityTestTemplate';
import loadFramework from '../frameworks/frameworkL... |
const isDisabled = (parameter: any) =>
parameter === false || (parameter && parameter.disable === true);
function testStorySnapshots(options: StoryshotsOptions = {}) {
if (typeof describe !== 'function') {
throw new Error('testStorySnapshots is intended only to be used inside jest');
}
addons.setChannel... | {
methods.forEach(method => {
if (typeof testMethod[method] === 'function') {
global[method](testMethod[method], testMethod[method].timeout);
}
});
} | identifier_body |
index.ts | import global, { describe } from 'global';
import addons, { mockChannel } from '@storybook/addons';
import ensureOptionsDefaults from './ensureOptionsDefaults';
import snapshotsTests from './snapshotsTestsTemplate';
import integrityTest from './integrityTestTemplate';
import loadFramework from '../frameworks/frameworkL... |
}
export default testStorySnapshots;
| {
throw new Error('storyshots found 0 stories');
} | conditional_block |
index.ts | import global, { describe } from 'global';
import addons, { mockChannel } from '@storybook/addons';
import ensureOptionsDefaults from './ensureOptionsDefaults';
import snapshotsTests from './snapshotsTestsTemplate';
import integrityTest from './integrityTestTemplate';
import loadFramework from '../frameworks/frameworkL... | (options: StoryshotsOptions = {}) {
if (typeof describe !== 'function') {
throw new Error('testStorySnapshots is intended only to be used inside jest');
}
addons.setChannel(mockChannel());
const { storybook, framework, renderTree, renderShallowTree } = loadFramework(options);
const {
asyncJest,
... | testStorySnapshots | identifier_name |
api.project.js | const debug = require('debug')('cygnus:api:project');
const express = require('express');
const router = express.Router();
const ProjectService = require('../service/srv.project');
// Get all actived projects.
router.get('/all', (req, res) => {
var service = new ProjectService();
service.getAllProjects(true)
... |
var service = new ProjectService();
service.getProjectById(prjId)
.then(ret => {
res.json({
code: 0,
data: ret
});
})
.fail(err => {
res.status(500).send('GET /project/:id error');
});
});
module.exports = ... | {
prjId = parseInt(prjId);
} | conditional_block |
api.project.js | const debug = require('debug')('cygnus:api:project');
const express = require('express');
const router = express.Router();
const ProjectService = require('../service/srv.project');
// Get all actived projects.
router.get('/all', (req, res) => {
var service = new ProjectService();
service.getAllProjects(true)
... | .then(ret => {
res.json({
code: 0,
data: ret
});
})
.fail(err => {
res.status(500).send('GET /project/:id error');
});
});
module.exports = router; | var service = new ProjectService();
service.getProjectById(prjId) | random_line_split |
gone-postal.js | (function(){
var app = angular.module('postal', []);
app.controller('ResultsController',function(){
this.items = saves;
});
//I think this is the code needed to read in data from a JSON file, it doesn't work locally because of browser security. ReQuires a small change to the html
... |
var saves = [
{
month: "1st September 2014",
amount: 280,
},
{
month:"1st October 2014",
amount: 210,
},
{
month:"1st November 2014",
amount:210,
},
{
month:"1st December 201... | .then(function(res){
$scope.monthly_sample = res.data
});
}); | random_line_split |
main.py | """
@created_at 2014-07-15
@author Exequiel Fuentes <efulet@gmail.com>
@author Brian Keith <briankeithn@gmail.com>
"""
# Se recomienda seguir los siguientes estandares:
# 1. Para codificacion: PEP 8 - Style Guide for Python Code (http://legacy.python.org/dev/peps/pep-0008/)
# 2. Para documentacion: PEP 257 - Docst... | print("**************")
# Implementacion propia del clasificador.
fknb = FKNaiveBayesClassifier()
fknb.fit(my_pca_lda.fk_get_lda_train(), my_pca_lda.fk_get_y_train())
y_pred_FK = fknb.predict(my_pca_lda.fk_get_lda_test())
print("FK_Bayes")
print(... | try:
# Verificar version de python
check_version()
# Cargar los datos
my_pca_lda = FKSkLearn(os.path.join(db_path(), "datos_diabetes.npz"))
# Preparar los datos para validacion
my_pca_lda.fk_train_test_split()
# Se entrena el clasificado... | conditional_block |
main.py | """
@created_at 2014-07-15
@author Exequiel Fuentes <efulet@gmail.com>
@author Brian Keith <briankeithn@gmail.com>
"""
# Se recomienda seguir los siguientes estandares:
# 1. Para codificacion: PEP 8 - Style Guide for Python Code (http://legacy.python.org/dev/peps/pep-0008/)
# 2. Para documentacion: PEP 257 - Docst... |
def db_path():
"""Retorna el path de las base de datos"""
pathfile = os.path.dirname(os.path.abspath(__file__))
return os.path.join(pathfile, "db")
if __name__ == "__main__":
try:
# Verificar version de python
check_version()
# Cargar los datos
my_pca_lda = F... | """Python v2.7 es requerida por el curso, entonces verificamos la version"""
if sys.version_info[:2] != (2, 7):
raise Exception("Parece que python v2.7 no esta instalado en el sistema") | identifier_body |
main.py | """
@created_at 2014-07-15
@author Exequiel Fuentes <efulet@gmail.com>
@author Brian Keith <briankeithn@gmail.com>
"""
# Se recomienda seguir los siguientes estandares:
# 1. Para codificacion: PEP 8 - Style Guide for Python Code (http://legacy.python.org/dev/peps/pep-0008/)
# 2. Para documentacion: PEP 257 - Docst... | ():
"""Python v2.7 es requerida por el curso, entonces verificamos la version"""
if sys.version_info[:2] != (2, 7):
raise Exception("Parece que python v2.7 no esta instalado en el sistema")
def db_path():
"""Retorna el path de las base de datos"""
pathfile = os.path.dirname(os.path.abspath(__fi... | check_version | identifier_name |
main.py | """
@created_at 2014-07-15
@author Exequiel Fuentes <efulet@gmail.com>
@author Brian Keith <briankeithn@gmail.com>
"""
# Se recomienda seguir los siguientes estandares:
# 1. Para codificacion: PEP 8 - Style Guide for Python Code (http://legacy.python.org/dev/peps/pep-0008/)
# 2. Para documentacion: PEP 257 - Docst... |
# Se verifica si la lista esta vacia.
if y_pred_SK == y_pred_FK:
print "Son iguales los dos metodos!"
else:
print "No son iguales. :("
# Se grafica la informacion.
graph = Graph(my_pca_lda.fk_get_lda_train(), my_pca_lda.fk_get_y_train())
... | # Esto es para verificar que las predicciones son iguales, deberia entregar una lista vacia.
print("...probando igualdad...")
y_pred_SK = [int(i) for i in my_pca_lda.fk_get_y_pred()]
#print y_pred_SK
#print y_pred_FK | random_line_split |
configure-dropbox.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { DropDownElement } from 'app/shared/models/drop-down-element';
import { DeploymentCenterStateManager } from 'app/site/deployment-center/deployment-center-setup/wizard-logic/deployment-center-state-manager';
import { CacheService } from 'app/shared/se... | (): void {
this._ngUnsubscribe$.next();
}
updateFormValidation() {
const required = new RequiredValidator(this._translateService, false);
this.wizard.sourceSettings.get('repoUrl').setValidators(required.validate.bind(required));
this.wizard.sourceSettings.get('branch').setValidators([]);
this.w... | ngOnDestroy | identifier_name |
configure-dropbox.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { DropDownElement } from 'app/shared/models/drop-down-element';
import { DeploymentCenterStateManager } from 'app/site/deployment-center/deployment-center-setup/wizard-logic/deployment-center-state-manager';
import { CacheService } from 'app/shared/se... | options.push({
displayLabel: siteName,
value: `${DeploymentCenterConstants.dropboxUri}/${siteName}`,
});
rawFolders.entries.forEach(item => {
if (siteName.toLowerCase() === item.name.toLowerCase() || item['.tag'] !== 'folder') {
} else {
... | {
this.foldersLoading = true;
this.folderList = [];
return this._cacheService
.post(Constants.serviceHost + 'api/dropbox/passthrough', true, null, {
url: `${DeploymentCenterConstants.dropboxApiUrl}/files/list_folder`,
authToken: this.wizard.getToken(),
arg: {
path: ''... | identifier_body |
configure-dropbox.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { DropDownElement } from 'app/shared/models/drop-down-element';
import { DeploymentCenterStateManager } from 'app/site/deployment-center/deployment-center-setup/wizard-logic/deployment-center-state-manager';
import { CacheService } from 'app/shared/se... |
});
this.folderList = options;
this.selectedFolder = `${DeploymentCenterConstants.dropboxUri}/${siteName}`;
},
err => {
this.foldersLoading = false;
this._logService.error(LogCategories.cicd, '/fetch-dropbox-folders', err);
}
);
}
}
| {
options.push({
displayLabel: item.name,
value: `${DeploymentCenterConstants.dropboxUri}/${item.name}`,
});
} | conditional_block |
configure-dropbox.component.ts | import { Component, OnInit, OnDestroy } from '@angular/core';
import { DropDownElement } from 'app/shared/models/drop-down-element';
import { DeploymentCenterStateManager } from 'app/site/deployment-center/deployment-center-setup/wizard-logic/deployment-center-state-manager';
import { CacheService } from 'app/shared/se... | export class ConfigureDropboxComponent implements OnInit, OnDestroy {
private _resourceId: string;
public folderList: DropDownElement<string>[] = [];
private _ngUnsubscribe$ = new Subject();
selectedFolder = '';
public foldersLoading = false;
constructor(
public wizard: DeploymentCenterStateManager,
... | styleUrls: ['./configure-dropbox.component.scss', '../step-configure.component.scss', '../../deployment-center-setup.component.scss'],
}) | random_line_split |
lexer.py | #!/usr/bin/python
from fsm import parse_automaton, accept
import re
__author__ = 'Roland'
import sys
keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif',
'else', 'while', 'or', 'and', 'not']
operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '... | fip.append((codif.index(atom), 0))
else:
if accept(*var_aut, string=atom) == True:
fip.append((0, get_poz(atom, ts_ident)))
elif accept(*num_aut, string=atom) == True:
fip.append((1, get_poz(atom, ts_const)))
... | if len(atom.strip()) == 0 and not in_string:
continue
if '"' in atom:
if in_string:
in_string += atom
if re.search('[^ "a-zA-Z0-9]', in_string):
error(i, " invalid character in string constant")
... | conditional_block |
lexer.py | #!/usr/bin/python
from fsm import parse_automaton, accept
import re
__author__ = 'Roland'
import sys
keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif',
'else', 'while', 'or', 'and', 'not']
operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '... | "s 0-9 s F",
"s [ t",
"t 0-9 f",
"f 0-9 f",
"f ] l F"]
var_aut = parse_automaton(var_lang)
num_lang = ["i 0 s B",
"i 1-9 t B",
"s . n",
"t 0-9 f", "t . n", "f 0-9 f", "f . n", "n 0-9 n F"]
num_aut = parse_automaton(num_lang)... | "s A-z s F", | random_line_split |
lexer.py | #!/usr/bin/python
from fsm import parse_automaton, accept
import re
__author__ = 'Roland'
import sys
keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif',
'else', 'while', 'or', 'and', 'not']
operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '... |
class binary_tree(object):
"""
Binary search tree. It remembers the order in which elements were added.
"""
def __init__(self, value):
"""
Constructor
"""
self.value = value
if self.value:
self.elements = [value]
else:
s... | """
Helper function to return string, even if given a tree, string or None
"""
if tree is None:
return 'None'
else:
if type(tree) == str:
return tree
return str(tree.value) | identifier_body |
lexer.py | #!/usr/bin/python
from fsm import parse_automaton, accept
import re
__author__ = 'Roland'
import sys
keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif',
'else', 'while', 'or', 'and', 'not']
operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '... | (self, value):
"""
Search for `value` in the tree.
"""
if value == self.value:
return True
return (self.left and value in self.left) or (self.right and value in self.right)
def index(self, value):
"""
Return the parent and sibling node of ... | __contains__ | identifier_name |
fortran_parser_test.py | #!/usr/bin/env python
#
# ParameterWeaver: a code generator to handle command line parameters
# and configuration files for C/C++/Fortran/R/Octave
# Copyright (C) 2013 Geert Jan Bex <geertjan.bex@uhasselt.be>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... | (unittest.TestCase):
'''Tests for Fortran parameter definition parser'''
def setUp(self):
'''Set up parameter list to be expected from valid viles'''
self._parameters = [
Parameter(Integer(), 'a', '10'),
Parameter(DoublePrecision(), 'f', '0.19D00'),
Parameter... | FortranParserTest | identifier_name |
fortran_parser_test.py | #!/usr/bin/env python
#
# ParameterWeaver: a code generator to handle command line parameters
# and configuration files for C/C++/Fortran/R/Octave
# Copyright (C) 2013 Geert Jan Bex <geertjan.bex@uhasselt.be>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... |
if __name__ == '__main__':
unittest.main()
| '''Parse a simple file that is well-formed and valid'''
file_name = 'tests/good_fortran.txt'
t = CharacterArray()
try:
self.assertEqual(self._parameters, self._parser.parse(file_name))
except ParameterDefinitionError as error:
self.fail(str(error)) | identifier_body |
fortran_parser_test.py | #!/usr/bin/env python
#
# ParameterWeaver: a code generator to handle command line parameters
# and configuration files for C/C++/Fortran/R/Octave
# Copyright (C) 2013 Geert Jan Bex <geertjan.bex@uhasselt.be>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... | unittest.main() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.