uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d129c1499c10abb7b0218936 | train | class | class GifWriter(object):
def __init__(self, temp_format, dest_gif):
try:
sysstr = platform.system()
if sysstr =="Windows":
subprocess.check_call(
['magick'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
subproc... | class GifWriter(object):
| def __init__(self, temp_format, dest_gif):
try:
sysstr = platform.system()
if sysstr =="Windows":
subprocess.check_call(
['magick'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
subprocess.check_call(
... | import subprocess
import os
import platform
from scipy.misc import imsave
class GifWriter(object):
| 21 | 87 | 291 | 5 | 15 | ReynoldZhao/Project4_Stereo | src/gifwriter.py | Python | GifWriter | GifWriter | 8 | 46 | 8 | 9 | 4d4b56738c8b0300cbecae2e3f55f88ab4fe8dda | bigcode/the-stack | train |
31a635971df8bf4ffa5fb730 | train | class | class Background(object):
def __init__(self, background_lensmodel, z_background, z_source):
self._halos_lensmodel = background_lensmodel
self._z_background = z_background
self._z_source = z_source
def ray_shooting(self, alphax, alphay, args, x_in, y_in):
x, y, _, _ = self._ha... | class Background(object):
| def __init__(self, background_lensmodel, z_background, z_source):
self._halos_lensmodel = background_lensmodel
self._z_background = z_background
self._z_source = z_source
def ray_shooting(self, alphax, alphay, args, x_in, y_in):
x, y, _, _ = self._halos_lensmodel.lens_model.ra... | , 'y': y, 'alphax': alphax, 'alphay': alphay}
return self._rays[offset_index]['x'], self._rays[offset_index]['y'],\
self._rays[offset_index]['alphax'], self._rays[offset_index]['alphay']
class Background(object):
| 66 | 66 | 221 | 4 | 62 | Jasonpoh/lenstronomy_sims | lenstronomy/LensModel/Optimizer/multi_plane_optimizer.py | Python | Background | Background | 303 | 323 | 303 | 304 | 9426f1f8bd5fda8c991b12e09f09cdf9c05c2534 | bigcode/the-stack | train |
8bf9e6b74307b091de1dde94 | train | class | class MultiPlaneLensing(object):
_no_potential = True
def __init__(self, full_lensmodel, x_pos, y_pos, lensmodel_params, z_source,
z_macro, astropy_instance, macro_indicies, optimizer_kwargs, numerical_alpha_class):
"""
This class performs (fast) lensing computations for mult... | class MultiPlaneLensing(object):
| _no_potential = True
def __init__(self, full_lensmodel, x_pos, y_pos, lensmodel_params, z_source,
z_macro, astropy_instance, macro_indicies, optimizer_kwargs, numerical_alpha_class):
"""
This class performs (fast) lensing computations for multi-plane lensing scenarios
... | from lenstronomy.LensModel.lens_model import LensModel
import numpy as np
from lenstronomy.Util.util import approx_theta_E
class MultiPlaneLensing(object):
| 37 | 256 | 2,460 | 7 | 29 | Jasonpoh/lenstronomy_sims | lenstronomy/LensModel/Optimizer/multi_plane_optimizer.py | Python | MultiPlaneLensing | MultiPlaneLensing | 5 | 245 | 5 | 6 | cf98fc54716cceaf25b0f1a5cb3f6a829ec6351c | bigcode/the-stack | train |
fafde0135845f58d107657ed | train | class | class ToVary(object):
def __init__(self,tovary_lensmodel,z_to_vary):
self._tovary_lensmodel = tovary_lensmodel
self._z_to_vary = z_to_vary
def ray_shooting(self, thetax, thetay, args, x_in, y_in):
x, y, alphax, alphay = self._tovary_lensmodel.lens_model. \
ray_shooting_pa... | class ToVary(object):
| def __init__(self,tovary_lensmodel,z_to_vary):
self._tovary_lensmodel = tovary_lensmodel
self._z_to_vary = z_to_vary
def ray_shooting(self, thetax, thetay, args, x_in, y_in):
x, y, alphax, alphay = self._tovary_lensmodel.lens_model. \
ray_shooting_partial(x_in, y_in, theta... | mo=self._astropy_instance,
multi_plane=True, z_source=self._z_source, numerical_alpha_class=numerical_alpha_class)
return macromodel, macro_args, halo_lensmodel, halo_args, front_lensmodel,front_args,\
background_z_current
class ToVary(object):
| 64 | 64 | 157 | 6 | 57 | Jasonpoh/lenstronomy_sims | lenstronomy/LensModel/Optimizer/multi_plane_optimizer.py | Python | ToVary | ToVary | 247 | 260 | 247 | 248 | 481293c02ba5654bbc88ee2200760abd1a2fb327 | bigcode/the-stack | train |
bf32f79c3f164047b4a00032 | train | class | class Foreground(object):
def __init__(self, foreground_lensmodel, z_to_vary, x_pos, y_pos, precompupted_rays = None):
self._halos_lensmodel = foreground_lensmodel
self._z_to_vary = z_to_vary
self._x_pos, self._y_pos = x_pos, y_pos
if precompupted_rays is None:
self._r... | class Foreground(object):
| def __init__(self, foreground_lensmodel, z_to_vary, x_pos, y_pos, precompupted_rays = None):
self._halos_lensmodel = foreground_lensmodel
self._z_to_vary = z_to_vary
self._x_pos, self._y_pos = x_pos, y_pos
if precompupted_rays is None:
self._rays = [None] * 3
el... | ary_lensmodel = tovary_lensmodel
self._z_to_vary = z_to_vary
def ray_shooting(self, thetax, thetay, args, x_in, y_in):
x, y, alphax, alphay = self._tovary_lensmodel.lens_model. \
ray_shooting_partial(x_in, y_in, thetax, thetay, z_start=self._z_to_vary,
... | 134 | 134 | 448 | 5 | 128 | Jasonpoh/lenstronomy_sims | lenstronomy/LensModel/Optimizer/multi_plane_optimizer.py | Python | Foreground | Foreground | 262 | 301 | 262 | 263 | dfb6d2110b2f9d7ab5eb0cf8fef68f25bbde47ac | bigcode/the-stack | train |
a4702a20b1c43515365a851b | train | function | def linear(args, output_size, bias, bias_start=0.0, scope=None):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bias term or not.
bias_start: sta... | def linear(args, output_size, bias, bias_start=0.0, scope=None):
| """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bias term or not.
bias_start: starting value to initialize the bias; 0 by default.
scope: Vari... | ValueError: If len(inputs) is different from len(targets) or len(weights).
"""
with tf.name_scope(values=inputs + targets + weights, name=name,
default_name='sampled_sequence_loss'):
cost = tf.reduce_sum(sequence_loss_by_example(
inputs, targets, weights, loss_function,
ave... | 138 | 138 | 461 | 19 | 118 | 873040/Abhishek | research/textsum/seq2seq_lib.py | Python | linear | linear | 92 | 137 | 92 | 92 | aa323f5c7f1bdb17bd001967624e6fe9293c0299 | bigcode/the-stack | train |
3408684aae355532fdfe4408 | train | function | def sequence_loss_by_example(inputs, targets, weights, loss_function,
average_across_timesteps=True, name=None):
"""Sampled softmax loss for a sequence of inputs (per example).
Args:
inputs: List of 2D Tensors of shape [batch_size x hid_dim].
targets: List of 1D batch-sized int... | def sequence_loss_by_example(inputs, targets, weights, loss_function,
average_across_timesteps=True, name=None):
| """Sampled softmax loss for a sequence of inputs (per example).
Args:
inputs: List of 2D Tensors of shape [batch_size x hid_dim].
targets: List of 1D batch-sized int32 Tensors of the same length as logits.
weights: List of 1D batch-sized float-Tensors of the same length as logits.
loss_function: Sa... | 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.
# ===============================================... | 120 | 120 | 400 | 25 | 95 | 873040/Abhishek | research/textsum/seq2seq_lib.py | Python | sequence_loss_by_example | sequence_loss_by_example | 23 | 56 | 23 | 24 | a1138ba8f7a4b069ea67a3f6dd8f17355f83746d | bigcode/the-stack | train |
6f2c64384a514a04ec230f4e | train | function | def sampled_sequence_loss(inputs, targets, weights, loss_function,
average_across_timesteps=True,
average_across_batch=True, name=None):
"""Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
inputs: List of 2D Tensors of shape [batch... | def sampled_sequence_loss(inputs, targets, weights, loss_function,
average_across_timesteps=True,
average_across_batch=True, name=None):
| """Weighted cross-entropy loss for a sequence of logits, batch-collapsed.
Args:
inputs: List of 2D Tensors of shape [batch_size x hid_dim].
targets: List of 1D batch-sized int32 Tensors of the same length as inputs.
weights: List of 1D batch-sized float-Tensors of the same length as inputs.
loss_fu... | log_perps = tf.add_n(log_perp_list)
if average_across_timesteps:
total_size = tf.add_n(weights)
total_size += 1e-12 # Just to avoid division by 0 for all-0 weights.
log_perps /= total_size
return log_perps
def sampled_sequence_loss(inputs, targets, weights, loss_function,
... | 98 | 98 | 327 | 31 | 66 | 873040/Abhishek | research/textsum/seq2seq_lib.py | Python | sampled_sequence_loss | sampled_sequence_loss | 59 | 89 | 59 | 61 | 9681a195582e55089e9b8cdf217f4392cd1690eb | bigcode/the-stack | train |
471a8bb24f3c802e1b7a774c | train | class | class PyRoute2(ip_command.IpCommand):
def _ip_link(self, ip, command, check_exit_code, **kwargs):
try:
LOG.debug('pyroute2 command %(command)s, arguments %(args)s' %
{'command': command, 'args': kwargs})
return ip.link(command, **kwargs)
except ipexc.Ne... | class PyRoute2(ip_command.IpCommand):
| def _ip_link(self, ip, command, check_exit_code, **kwargs):
try:
LOG.debug('pyroute2 command %(command)s, arguments %(args)s' %
{'command': command, 'args': kwargs})
return ip.link(command, **kwargs)
except ipexc.NetlinkError as e:
with excut... | # 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 writing, software
# d... | 223 | 256 | 1,044 | 10 | 213 | wmousa/os-vif | os_vif/internal/ip/linux/impl_pyroute2.py | Python | PyRoute2 | PyRoute2 | 26 | 123 | 26 | 27 | 90583a51f90cb5e908401ffea562cd9c55967592 | bigcode/the-stack | train |
2c3cb7d5732f67006bc615f6 | train | class | class Migration(DataMigration):
def forwards(self, orm):
"""Set site domain and name."""
Site = orm['sites.Site']
site = Site.objects.get(id=settings.SITE_ID)
site.domain = "cookiecutter-project.herokuapp.com"
site.name = "cookiecutter-project"
site.save()
def b... | class Migration(DataMigration):
| def forwards(self, orm):
"""Set site domain and name."""
Site = orm['sites.Site']
site = Site.objects.get(id=settings.SITE_ID)
site.domain = "cookiecutter-project.herokuapp.com"
site.name = "cookiecutter-project"
site.save()
def backwards(self, orm):
"""R... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.conf import settings
from django.db import models
class Migration(DataMigration):
| 42 | 256 | 1,010 | 5 | 36 | goldhand/cookiecutter-project | cookiecutter-project/users/migrations/0002_set_site_domain_and_name.py | Python | Migration | Migration | 9 | 73 | 9 | 10 | 7b78be96e63e89e15cfc03f73640b957f137066a | bigcode/the-stack | train |
fc2a6e70c506d776debfc7b0 | train | class | class Elasticsearch(object):
"""Class: ElasticSearch
Description: Class representation of the Elasticsearch class.
Methods:
__init__
"""
def __init__(self, host_list, port=9200):
"""Method: __init__
Description: Initialization instance of the class.
Argume... | class Elasticsearch(object):
| """Class: ElasticSearch
Description: Class representation of the Elasticsearch class.
Methods:
__init__
"""
def __init__(self, host_list, port=9200):
"""Method: __init__
Description: Initialization instance of the class.
Arguments:
"""
sel... |
import os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
import mock
# Local
sys.path.append(os.getcwd())
import elastic_class
import version
__version__ = version.__version__
class Elasticsearch(object):
| 63 | 64 | 84 | 4 | 59 | deepcoder42/elastic-lib | test/unit/elastic_class/elasticsearchstatus_chk_all.py | Python | Elasticsearch | Elasticsearch | 37 | 59 | 37 | 38 | 8923c86f44def6a48bf491e59708a36f2fbf7e7b | bigcode/the-stack | train |
e46783b9b641b869272d122c | train | class | class UnitTest(unittest.TestCase):
"""Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_one_warn
test_default_no_warn
"""
def setUp(self):
"""Function: setUp
Description: Initialization for unit test... | class UnitTest(unittest.TestCase):
| """Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_one_warn
test_default_no_warn
"""
def setUp(self):
"""Function: setUp
Description: Initialization for unit testing.
Arguments:
""... | # Classification (U)
"""Program: elasticsearchstatus_chk_all.py
Description: Unit testing of chk_all in elastic_class.ElasticSearchStatus.
Usage:
test/unit/elastic_class/elasticsearchstatus_chk_all.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.ve... | 215 | 215 | 718 | 7 | 207 | deepcoder42/elastic-lib | test/unit/elastic_class/elasticsearchstatus_chk_all.py | Python | UnitTest | UnitTest | 62 | 166 | 62 | 63 | 750d55d1aa0187eede5d9e040800b908b0f1a841 | bigcode/the-stack | train |
d6be60f565e04184cd52bfe4 | train | function | def item1():
print('==== Generate Code Step By Step ====\n')
class_name = input("Please enter class name: ")
print("class name is:", class_name+"\n")
print("Please complete class details.")
class_fields_name = []
class_fields_type = []
class_fields_req = []
while True:
_name ... | def item1():
| print('==== Generate Code Step By Step ====\n')
class_name = input("Please enter class name: ")
print("class name is:", class_name+"\n")
print("Please complete class details.")
class_fields_name = []
class_fields_type = []
class_fields_req = []
while True:
_name = input("Ente... | ====================================================================================')
print('1. Generate Code Step By Step')
print('2. Generate Code By Existing Class')
print('3. Generate View Codes Step By Step')
print('4. Help')
print('5. About')
print('0. Exit')
print('==============================================... | 256 | 256 | 1,346 | 4 | 251 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | item1 | item1 | 61 | 214 | 61 | 61 | 681abebcc69df7672cc0e0242e988daee8931e5d | bigcode/the-stack | train |
7cb903dc625a584fc36b4726 | train | function | def item0():
exit()
| def item0():
| exit()
| path: output/views/" +
module_var+"create.htm")
print("Module file successfully created -> path: output/views/" +
module_var+"update.htm")
def item4():
print("this is item 4")
def item5():
print("this is item 5")
def item0():
| 64 | 64 | 7 | 4 | 60 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | item0 | item0 | 504 | 505 | 504 | 504 | 87a39007a7c245b9d4d15b6458e3dd2a20c22d58 | bigcode/the-stack | train |
77cf33750c10b4031256965c | train | function | def getInput():
global inp_value
inp_value = input("Select Menu Item:")
while not inp_value.isnumeric():
print("Please enter a number.")
inp_value = input("Select Menu Item:")
return int(inp_value)
| def getInput():
| global inp_value
inp_value = input("Select Menu Item:")
while not inp_value.isnumeric():
print("Please enter a number.")
inp_value = input("Select Menu Item:")
return int(inp_value)
| print('1. Generate Code Step By Step')
print('2. Generate Code By Existing Class')
print('3. Generate View Codes Step By Step')
print('4. Help')
print('5. About')
print('0. Exit')
print('====================================================================================')
# accept only numeric input
def getInput():
| 64 | 64 | 51 | 4 | 59 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | getInput | getInput | 25 | 31 | 25 | 25 | 7e38b456b97475a2ff34b42e78cebcf004c120f4 | bigcode/the-stack | train |
b5cee592d7619602c3d2bbfb | train | function | def item2():
print("this is item 2")
| def item2():
| print("this is item 2")
| routeFile.close()
print("Class file successfully created -> path: output/database/"+class_name+".py")
print("Api file successfully created -> path: output/resources/"+_class_var+".py")
print("Route file successfully Edited -> path: output/routes/"+_class_var+".py")
def item2():
| 64 | 64 | 13 | 4 | 60 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | item2 | item2 | 217 | 218 | 217 | 217 | 8d5376913faa87d982e08ca545ab435b299eb15a | bigcode/the-stack | train |
09f41ee8e972f2cc7f917526 | train | function | def clearScreen():
os.system('cls' if os.name == 'nt' else 'clear')
| def clearScreen():
| os.system('cls' if os.name == 'nt' else 'clear')
| from genericpath import isdir
from art import *
import os
from pynput import keyboard
def clearScreen():
| 24 | 64 | 21 | 4 | 19 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | clearScreen | clearScreen | 7 | 8 | 7 | 7 | 3e84db1019c5dae278e945df837b9f0c78effeed | bigcode/the-stack | train |
c96f8f6cde6721daf8e807df | train | function | def item3():
def getType(field):
_type = ""
if field != "text" or field != "email" or field != "password":
_type = "text"
return _type
print('==== Generate Code Step By Step ====\n')
module_name = input("Please enter module name: ")
module_name_fa = input("Please e... | def item3():
| def getType(field):
_type = ""
if field != "text" or field != "email" or field != "password":
_type = "text"
return _type
print('==== Generate Code Step By Step ====\n')
module_name = input("Please enter module name: ")
module_name_fa = input("Please enter module n... | Message':'Successfully deleted.'}}), 200)
else:
return make_response(jsonify({{'Message': 'Not Found'}}), 200)
"""
#create api file
_class_var=class_name.lower()
apiFile = open("output/resources/"+_class_var+".py", "w")
apiFile.write(api_text.format(ClassName=class_nam... | 256 | 256 | 2,275 | 4 | 252 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | item3 | item3 | 221 | 493 | 221 | 221 | ea1876139ba672a9588ed171f169b274d55824b0 | bigcode/the-stack | train |
6f5cb1de004dae0ed6b157fb | train | function | def item4():
print("this is item 4")
| def item4():
| print("this is item 4")
| print("Module file successfully created -> path: output/views/"+module_var+"view.htm")
print("Module file successfully created -> path: output/views/" +
module_var+"create.htm")
print("Module file successfully created -> path: output/views/" +
module_var+"update.htm")
def item4():
| 64 | 64 | 13 | 4 | 60 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | item4 | item4 | 496 | 497 | 496 | 496 | fab0685ef6fd434b96595fafdc71811cf85b8bca | bigcode/the-stack | train |
b4848cf4348669fd0038baaa | train | function | def getFieldType(field):
_type = ""
if field == "string" or field == "str":
_type = "StringField"
elif field == "int":
_type = "IntField"
elif field == "float":
_type = "FloatField"
elif field == "bool" or field == "boolean":
_type = "BooleanField"
elif field ... | def getFieldType(field):
| _type = ""
if field == "string" or field == "str":
_type = "StringField"
elif field == "int":
_type = "IntField"
elif field == "float":
_type = "FloatField"
elif field == "bool" or field == "boolean":
_type = "BooleanField"
elif field == "datetime":
_t... | def getInput():
global inp_value
inp_value = input("Select Menu Item:")
while not inp_value.isnumeric():
print("Please enter a number.")
inp_value = input("Select Menu Item:")
return int(inp_value)
# check and return field type
def getFieldType(field):
| 64 | 64 | 124 | 6 | 57 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | getFieldType | getFieldType | 36 | 56 | 36 | 36 | bc1461e756f9c46bdda1fd8edbc3cd93a3fcdd75 | bigcode/the-stack | train |
46e1adf1182055118980e686 | train | function | def item5():
print("this is item 5")
| def item5():
| print("this is item 5")
| _var+"view.htm")
print("Module file successfully created -> path: output/views/" +
module_var+"create.htm")
print("Module file successfully created -> path: output/views/" +
module_var+"update.htm")
def item4():
print("this is item 4")
def item5():
| 64 | 64 | 13 | 4 | 60 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | item5 | item5 | 500 | 501 | 500 | 500 | 1c03547950313cf5aba9be360dca8739652dd6b9 | bigcode/the-stack | train |
15166553ba17cbd17fa3b6c4 | train | function | def main(func_keys, user_cmd):
count = len(func_keys.keys())
if count > int(user_cmd):
func_keys[user_cmd]()
else:
print("There is no items, please select other item.")
| def main(func_keys, user_cmd):
| count = len(func_keys.keys())
if count > int(user_cmd):
func_keys[user_cmd]()
else:
print("There is no items, please select other item.")
| 5")
def item0():
exit()
func_keys = {
'0': item0,
'1': item1,
'2': item2,
'3': item3,
'4': item4,
'5': item5,
}
def main(func_keys, user_cmd):
| 64 | 64 | 46 | 8 | 56 | HamdiReza/FlaskRestFulCodeGenerator | app.py | Python | main | main | 518 | 523 | 518 | 518 | 432e6ad5a21c06eafbe06f49204c30e042825611 | bigcode/the-stack | train |
6c2b75321c91583ffe808464 | train | function | @register.inclusion_tag("grades_semester_menu.html")
def include_grades_semester_menu():
return dict(semesters=Semester.objects.all()[:5])
| @register.inclusion_tag("grades_semester_menu.html")
def include_grades_semester_menu():
| return dict(semesters=Semester.objects.all()[:5])
| from django.template import Library
from evap.evaluation.models import Semester
register = Library()
@register.inclusion_tag("grades_semester_menu.html")
def include_grades_semester_menu():
| 38 | 64 | 34 | 20 | 18 | JenniferStamm/EvaP | evap/grades/templatetags/grades_templatetags.py | Python | include_grades_semester_menu | include_grades_semester_menu | 8 | 10 | 8 | 9 | eebc2148a80b1f072f085472837751b73522fa5a | bigcode/the-stack | train |
26219cff1cb974b526715e7f | train | class | class UserMediaPage(Base):
_audio_button_locator = (By.CSS_SELECTOR, 'button[data-type="startAudioButton"]')
_frame_locator = (By.CSS_SELECTOR, "#test-iframe[src*='getusermedia']")
def switch_to_frame(self):
self.wait_for_element_displayed(*self._frame_locator)
get_user_media_frame = s... | class UserMediaPage(Base):
| _audio_button_locator = (By.CSS_SELECTOR, 'button[data-type="startAudioButton"]')
_frame_locator = (By.CSS_SELECTOR, "#test-iframe[src*='getusermedia']")
def switch_to_frame(self):
self.wait_for_element_displayed(*self._frame_locator)
get_user_media_frame = self.marionette.find_element(*se... |
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from gaiatest.apps.base import Base
class UserMediaPage(Base):
| 64 | 64 | 140 | 7 | 56 | dcoloma/gaia | tests/python/gaia-ui-tests/gaiatest/apps/ui_tests_privileged/regions/user_media.py | Python | UserMediaPage | UserMediaPage | 9 | 21 | 9 | 9 | 312c7872cfae8d31b7bbcf7ba0a66b2e3265a964 | bigcode/the-stack | train |
06ab53f01e23b8d4e6f97692 | train | function | def update_statistics(pcap_statistics, pkt_tuple, record, protocol, len_name):
if pkt_tuple in pcap_statistics:
return update_statistics_info(pcap_statistics,pkt_tuple,record,True, protocol, len_name)
else:
return update_statistics_info(pcap_statistics,reverse_pkt_tuple(pkt_tuple),record, Fals... | def update_statistics(pcap_statistics, pkt_tuple, record, protocol, len_name):
| if pkt_tuple in pcap_statistics:
return update_statistics_info(pcap_statistics,pkt_tuple,record,True, protocol, len_name)
else:
return update_statistics_info(pcap_statistics,reverse_pkt_tuple(pkt_tuple),record, False, protocol, len_name)
| 1]['bwd_packets']['pkt_len'] += [record[len_name]]
pcap_statistics[pkt_tuple][-1]['bwd_packets']['arrival_time'] += [record['frame.time_relative']]
return pcap_statistics
def update_statistics(pcap_statistics, pkt_tuple, record, protocol, len_name):
| 64 | 64 | 75 | 18 | 45 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | update_statistics | update_statistics | 68 | 72 | 68 | 68 | 47e75bb3efb3068b6cc0e06c0232b49e2e0de0ea | bigcode/the-stack | train |
6769bcd2321ea38aaaec19e7 | train | function | def sample_trace(raw_trace_df,sampling_rate):
import time
return raw_trace_df.sample(frac=sampling_rate, random_state=int(time.time()))
| def sample_trace(raw_trace_df,sampling_rate):
| import time
return raw_trace_df.sample(frac=sampling_rate, random_state=int(time.time()))
| return _generate_flow_features(raw_trace_df, 'tcp.stream', 'tcp.len', sampling_rate, upsampled)
else:
return _track_flow(raw_trace_df, 'tcp', 'tcp.len', max_byte_per_flow=max_byte_per_flow)
def sample_trace(raw_trace_df,sampling_rate):
| 64 | 64 | 32 | 10 | 54 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | sample_trace | sample_trace | 214 | 216 | 214 | 214 | 96d1472a78acd887d55df493994609010ee44db4 | bigcode/the-stack | train |
70b6004adf6a1a7f1c2fe420 | train | function | def flatten_dict(pcap_statistics):
result_dict = []
for _, flow_list in pcap_statistics.items():
for flow in flow_list:
flow = calculate_flow_statistics(flow)
result_dict.append(flow)
return result_dict
| def flatten_dict(pcap_statistics):
| result_dict = []
for _, flow_list in pcap_statistics.items():
for flow in flow_list:
flow = calculate_flow_statistics(flow)
result_dict.append(flow)
return result_dict
| _len = np.std(flow['fwd_packets']['pkt_len'] + flow['bwd_packets']['pkt_len'],ddof=1)
flow['stddev(pkt_len)'] = std_pkt_len if not np.isnan(std_pkt_len) else -1
return flow
def flatten_dict(pcap_statistics):
| 64 | 64 | 49 | 7 | 56 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | flatten_dict | flatten_dict | 90 | 96 | 90 | 90 | d3a052620ecb36386890a70b11ec9379b472a106 | bigcode/the-stack | train |
c7cf460fac202d53546d88ac | train | function | def last_flow_exceed_byte_count(record, pcap_statistics, protocol, max_byte_per_flow):
pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
flow_list = pcap_statistics[pkt_tuple] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple]
last... | def last_flow_exceed_byte_count(record, pcap_statistics, protocol, max_byte_per_flow):
| pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
flow_list = pcap_statistics[pkt_tuple] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple]
last_flow = flow_list[-1]
byte_count = record['udp.length'] if protocol == 'udp' else r... | reversed_pkt_tuple][-1]
pkt_len = len(last_flow['fwd_packets']['pkt_len']) + len(last_flow['bwd_packets']['pkt_len'])
return pkt_len >= max_packets_per_flow
def last_flow_exceed_byte_count(record, pcap_statistics, protocol, max_byte_per_flow):
| 64 | 64 | 148 | 20 | 43 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | last_flow_exceed_byte_count | last_flow_exceed_byte_count | 105 | 112 | 105 | 105 | 81307f72955dff9c17e9515e12e7f63cf04f8967 | bigcode/the-stack | train |
d3d915bbb6fed12aed416f32 | train | function | def _track_flow(pcap_df, protocol, len_name, max_byte_per_flow=None):
def helper(pcap_statistics, row):
pkt_tuple = extract_packet_tuple(row, protocol)
if not is_in(row, pcap_statistics, protocol) or last_flow_exceed_byte_count(row, pcap_statistics, protocol, max_byte_per_flow):
add_in_s... | def _track_flow(pcap_df, protocol, len_name, max_byte_per_flow=None):
| def helper(pcap_statistics, row):
pkt_tuple = extract_packet_tuple(row, protocol)
if not is_in(row, pcap_statistics, protocol) or last_flow_exceed_byte_count(row, pcap_statistics, protocol, max_byte_per_flow):
add_in_statistics(pcap_statistics, pkt_tuple, row, protocol, len_name)
... | 'tcp' else None
byte_count += np.sum(last_flow['fwd_packets']['pkt_len']) + np.sum(last_flow['bwd_packets']['pkt_len'])
return byte_count >= max_byte_per_flow
def _track_flow(pcap_df, protocol, len_name, max_byte_per_flow=None):
| 64 | 64 | 194 | 19 | 44 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | _track_flow | _track_flow | 114 | 126 | 114 | 114 | 5ddf7e9b262a28055c59a61a289b621623410d63 | bigcode/the-stack | train |
120268d22996396d1d0d919b | train | function | def extract_useful_info(record, protocol, len_name):
useful_info = {\
"src_ip":record['ip.src'],\
"src_port":record[protocol + '.srcport'],\
"dst_ip":record['ip.dst'],\
"dst_port":record[protocol + '.dstport'],\
"rel_start":record['frame.time_relative'],\
'fwd_packets... | def extract_useful_info(record, protocol, len_name):
| useful_info = {\
"src_ip":record['ip.src'],\
"src_port":record[protocol + '.srcport'],\
"dst_ip":record['ip.dst'],\
"dst_port":record[protocol + '.dstport'],\
"rel_start":record['frame.time_relative'],\
'fwd_packets':{\
'pkt_len':[record['udp.length'] if p... | cap_statistics[pkt_tuple] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple]
last_flow = flow_list[-1]
return record['frame.time_relative'] - last_flow['rel_start'] > time_delta_threshold
def extract_useful_info(record, protocol, len_name):
| 64 | 64 | 166 | 12 | 51 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | extract_useful_info | extract_useful_info | 35 | 51 | 35 | 35 | 0286888b85086795653e0b3fa467547012964c63 | bigcode/the-stack | train |
e1aa91eb84186f74c16ce162 | train | function | def udp_generate(raw_trace_df,sampling_rate=1.0, upsampled=False, max_byte_per_flow=None):
if max_byte_per_flow is None:
return _generate_flow_features(raw_trace_df, 'udp.stream', 'udp.length', sampling_rate, upsampled)
else:
return _track_flow(raw_trace_df, 'udp', 'udp.length', max_byte_per_fl... | def udp_generate(raw_trace_df,sampling_rate=1.0, upsampled=False, max_byte_per_flow=None):
| if max_byte_per_flow is None:
return _generate_flow_features(raw_trace_df, 'udp.stream', 'udp.length', sampling_rate, upsampled)
else:
return _track_flow(raw_trace_df, 'udp', 'udp.length', max_byte_per_flow=max_byte_per_flow) | _per_flow=max_byte_per_flow)
def sample_trace(raw_trace_df,sampling_rate):
import time
return raw_trace_df.sample(frac=sampling_rate, random_state=int(time.time()))
def udp_generate(raw_trace_df,sampling_rate=1.0, upsampled=False, max_byte_per_flow=None):
| 64 | 64 | 88 | 25 | 39 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | udp_generate | udp_generate | 218 | 222 | 218 | 218 | 523e4c4daef683c97132f1224429e43a163a2b35 | bigcode/the-stack | train |
e7147e3cb1baab98220cd269 | train | function | def last_flow_exceed_time_duration(record, pcap_statistics, protocol, time_delta_threshold):
pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
flow_list = pcap_statistics[pkt_tuple] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple]
... | def last_flow_exceed_time_duration(record, pcap_statistics, protocol, time_delta_threshold):
| pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
flow_list = pcap_statistics[pkt_tuple] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple]
last_flow = flow_list[-1]
return record['frame.time_relative'] - last_flow['rel_start']... | pcap_statistics, protocol):
pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
return pkt_tuple in pcap_statistics or reversed_pkt_tuple in pcap_statistics
def last_flow_exceed_time_duration(record, pcap_statistics, protocol, time_delta_threshold):
| 64 | 64 | 98 | 19 | 44 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | last_flow_exceed_time_duration | last_flow_exceed_time_duration | 28 | 33 | 28 | 28 | b5da7ae0db613834cd915d1bcf85ff9cb72c65eb | bigcode/the-stack | train |
ba72b1818732f48ae7556102 | train | function | def add_in_statistics(pcap_statistics, packet_tuple, record, protocol, len_name):
if packet_tuple not in pcap_statistics:
pcap_statistics[packet_tuple] = []
pcap_statistics[packet_tuple].append(extract_useful_info(record, protocol, len_name))
return pcap_statistics
| def add_in_statistics(pcap_statistics, packet_tuple, record, protocol, len_name):
| if packet_tuple not in pcap_statistics:
pcap_statistics[packet_tuple] = []
pcap_statistics[packet_tuple].append(extract_useful_info(record, protocol, len_name))
return pcap_statistics
| 'arrival_time':[record['frame.time_relative']]\
},\
'bwd_packets':{\
'pkt_len':[],\
'arrival_time':[]\
}
}
return useful_info
def add_in_statistics(pcap_statistics, packet_tuple, record, protocol, len_name):
| 64 | 64 | 65 | 18 | 45 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | add_in_statistics | add_in_statistics | 53 | 57 | 53 | 53 | 2f931636f2ca75ca06c3738228c18258133103bc | bigcode/the-stack | train |
03546972bf301592dd02f55b | train | function | def is_in(record, pcap_statistics, protocol):
pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
return pkt_tuple in pcap_statistics or reversed_pkt_tuple in pcap_statistics
| def is_in(record, pcap_statistics, protocol):
| pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
return pkt_tuple in pcap_statistics or reversed_pkt_tuple in pcap_statistics
| .src'], record[protocol + '.srcport'], record['ip.dst'], record[protocol + '.dstport'])
def reverse_pkt_tuple(pkt_tuple):
return (pkt_tuple[2], pkt_tuple[3], pkt_tuple[0], pkt_tuple[1])
def is_in(record, pcap_statistics, protocol):
| 64 | 64 | 50 | 11 | 53 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | is_in | is_in | 23 | 26 | 23 | 23 | 2a3c6cd56a315750f77dd78fe2f7875c979a2ad0 | bigcode/the-stack | train |
3ee44029cf9fdea14cdc03ba | train | function | def reverse_pkt_tuple(pkt_tuple):
return (pkt_tuple[2], pkt_tuple[3], pkt_tuple[0], pkt_tuple[1])
| def reverse_pkt_tuple(pkt_tuple):
| return (pkt_tuple[2], pkt_tuple[3], pkt_tuple[0], pkt_tuple[1])
| address_v4)
except ipaddress.AddressValueError:
return False
return True
def extract_packet_tuple(record, protocol):
return (record['ip.src'], record[protocol + '.srcport'], record['ip.dst'], record[protocol + '.dstport'])
def reverse_pkt_tuple(pkt_tuple):
| 64 | 64 | 30 | 7 | 57 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | reverse_pkt_tuple | reverse_pkt_tuple | 20 | 21 | 20 | 20 | d0e3658988f61e24388c070f6cc9d315469c66d7 | bigcode/the-stack | train |
ec363c2653f9a877bef5b84f | train | function | def tcp_generate(raw_trace_df,sampling_rate=1.0, upsampled=False, max_byte_per_flow=None):
if max_byte_per_flow is None:
return _generate_flow_features(raw_trace_df, 'tcp.stream', 'tcp.len', sampling_rate, upsampled)
else:
return _track_flow(raw_trace_df, 'tcp', 'tcp.len', max_byte_per_flow=max... | def tcp_generate(raw_trace_df,sampling_rate=1.0, upsampled=False, max_byte_per_flow=None):
| if max_byte_per_flow is None:
return _generate_flow_features(raw_trace_df, 'tcp.stream', 'tcp.len', sampling_rate, upsampled)
else:
return _track_flow(raw_trace_df, 'tcp', 'tcp.len', max_byte_per_flow=max_byte_per_flow)
| _two_way_communication, len_name, sampling_rate, upsampled))
flow_df = pd.concat([flow_df,two_way_flow_df],axis=1)
return flow_df
def tcp_generate(raw_trace_df,sampling_rate=1.0, upsampled=False, max_byte_per_flow=None):
| 64 | 64 | 88 | 25 | 38 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | tcp_generate | tcp_generate | 208 | 212 | 208 | 208 | e669634b1ae08ad6f8703cd2c1f25678eb15b980 | bigcode/the-stack | train |
cce644f7bb5d03b863383dea | train | function | def extract_packet_tuple(record, protocol):
return (record['ip.src'], record[protocol + '.srcport'], record['ip.dst'], record[protocol + '.dstport'])
| def extract_packet_tuple(record, protocol):
| return (record['ip.src'], record[protocol + '.srcport'], record['ip.dst'], record[protocol + '.dstport'])
| '''
Is valid IPv4 address
'''
def _is_valid_ipv4(ipaddress_v4):
import ipaddress
try:
ipaddress.IPv4Address(ipaddress_v4)
except ipaddress.AddressValueError:
return False
return True
def extract_packet_tuple(record, protocol):
| 64 | 64 | 37 | 8 | 55 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | extract_packet_tuple | extract_packet_tuple | 17 | 18 | 17 | 17 | 46ff21d5a3388330518b71c3a9aba2cdea5243bd | bigcode/the-stack | train |
5f1c4332d3609995a1e23031 | train | function | def _generate_flow_features(raw_trace_df, stream_name, len_name, sampling_rate, upsampled):
trace_df = raw_trace_df
flow_df = pd.DataFrame()
# empty flow at the beginning
if trace_df.shape[0] == 0:
return flow_df
# transform illegal addresses to null
trace_df['src_addr'] = trace_df.app... | def _generate_flow_features(raw_trace_df, stream_name, len_name, sampling_rate, upsampled):
| trace_df = raw_trace_df
flow_df = pd.DataFrame()
# empty flow at the beginning
if trace_df.shape[0] == 0:
return flow_df
# transform illegal addresses to null
trace_df['src_addr'] = trace_df.apply(lambda row: None if pd.isnull(row['src_addr']) or not _is_valid_ipv4(row['ip.src']) else ... | = list(set(np.append(df['src_addr'].unique(), df['dst_addr'].unique())))
if len(addrs) != 2:
raise AssertionError()
# get forward features
stat = get_statistical_features(df, df['src_addr'] == addrs[0],len_name,'forw_pkt_len')
# get backward features
stat.update(get_statistical_featur... | 188 | 188 | 628 | 22 | 166 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | _generate_flow_features | _generate_flow_features | 162 | 206 | 162 | 162 | a7569845128a945cf1c16bf73b6180a25eb9a9ca | bigcode/the-stack | train |
1b54fdbebb9aac6a0155f5c8 | train | function | def last_flow_exceed_max_packets(record, pcap_statistics, protocol, max_packets_per_flow):
pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
last_flow = pcap_statistics[pkt_tuple][-1] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple][... | def last_flow_exceed_max_packets(record, pcap_statistics, protocol, max_packets_per_flow):
| pkt_tuple = extract_packet_tuple(record, protocol)
reversed_pkt_tuple = reverse_pkt_tuple(pkt_tuple)
last_flow = pcap_statistics[pkt_tuple][-1] if pkt_tuple in pcap_statistics else pcap_statistics[reversed_pkt_tuple][-1]
pkt_len = len(last_flow['fwd_packets']['pkt_len']) + len(last_flow['bwd_packets']['... | _statistics):
result_dict = []
for _, flow_list in pcap_statistics.items():
for flow in flow_list:
flow = calculate_flow_statistics(flow)
result_dict.append(flow)
return result_dict
def last_flow_exceed_max_packets(record, pcap_statistics, protocol, max_packets_per_flow):
| 64 | 64 | 111 | 20 | 43 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | last_flow_exceed_max_packets | last_flow_exceed_max_packets | 98 | 103 | 98 | 98 | 6b151dd19f28e8dfd6a907376e771692149ad2f6 | bigcode/the-stack | train |
8d888788645be9f2d2c7df32 | train | function | def _is_valid_ipv4(ipaddress_v4):
import ipaddress
try:
ipaddress.IPv4Address(ipaddress_v4)
except ipaddress.AddressValueError:
return False
return True
| def _is_valid_ipv4(ipaddress_v4):
| import ipaddress
try:
ipaddress.IPv4Address(ipaddress_v4)
except ipaddress.AddressValueError:
return False
return True
| import numpy as np
import pandas as pd
from tqdm import tqdm
import functools
'''
Is valid IPv4 address
'''
def _is_valid_ipv4(ipaddress_v4):
| 38 | 64 | 47 | 11 | 27 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | _is_valid_ipv4 | _is_valid_ipv4 | 9 | 15 | 9 | 9 | ed33b71f7d4dcc2ac9bd0d355aef32a4c3c88519 | bigcode/the-stack | train |
8bd089d4fce7bbba2d60e3f3 | train | function | def update_statistics_info(pcap_statistics,pkt_tuple,record,is_forward_stream, protocol, len_name):
if is_forward_stream:
pcap_statistics[pkt_tuple][-1]['fwd_packets']['pkt_len'] += [record[len_name]]
pcap_statistics[pkt_tuple][-1]['fwd_packets']['arrival_time'] += [record['frame.time_relative']]
... | def update_statistics_info(pcap_statistics,pkt_tuple,record,is_forward_stream, protocol, len_name):
| if is_forward_stream:
pcap_statistics[pkt_tuple][-1]['fwd_packets']['pkt_len'] += [record[len_name]]
pcap_statistics[pkt_tuple][-1]['fwd_packets']['arrival_time'] += [record['frame.time_relative']]
else:
pcap_statistics[pkt_tuple][-1]['bwd_packets']['pkt_len'] += [record[len_name]]
... | not in pcap_statistics:
pcap_statistics[packet_tuple] = []
pcap_statistics[packet_tuple].append(extract_useful_info(record, protocol, len_name))
return pcap_statistics
def update_statistics_info(pcap_statistics,pkt_tuple,record,is_forward_stream, protocol, len_name):
| 64 | 64 | 132 | 21 | 42 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | update_statistics_info | update_statistics_info | 59 | 66 | 59 | 59 | 61856ddd920f5be99b14fb097ebaa1b14c0558e5 | bigcode/the-stack | train |
f68e7667a122b88bdb2d36b1 | train | function | def calculate_flow_statistics(flow):
fwd_final_time = np.max(flow['fwd_packets']['arrival_time']) if len(flow['fwd_packets']['arrival_time']) > 0 else flow['rel_start']
bwd_final_time = np.max(flow['bwd_packets']['arrival_time']) if len(flow['bwd_packets']['arrival_time']) > 0 else flow['rel_start']
final_t... | def calculate_flow_statistics(flow):
| fwd_final_time = np.max(flow['fwd_packets']['arrival_time']) if len(flow['fwd_packets']['arrival_time']) > 0 else flow['rel_start']
bwd_final_time = np.max(flow['bwd_packets']['arrival_time']) if len(flow['bwd_packets']['arrival_time']) > 0 else flow['rel_start']
final_time = np.max([fwd_final_time, bwd_fin... | _name]]
pcap_statistics[pkt_tuple][-1]['bwd_packets']['arrival_time'] += [record['frame.time_relative']]
return pcap_statistics
def update_statistics(pcap_statistics, pkt_tuple, record, protocol, len_name):
if pkt_tuple in pcap_statistics:
return update_statistics_info(pcap_statistics,pkt_tup... | 114 | 114 | 380 | 6 | 108 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | calculate_flow_statistics | calculate_flow_statistics | 74 | 88 | 74 | 74 | 5819cabcb0682cc6e1ba077a450e0a2bf1760f9a | bigcode/the-stack | train |
201ada8995a056b675f58dca | train | function | def _calculate_two_way_communication(len_name, sampling_rate, upsampled, df):
# one-way statistics
def get_statistical_features(df, criter, feature_name,name_pred):
feature_avg = df[criter][feature_name].mean()
feature_avg = -1 if pd.isnull(feature_avg) else feature_avg
feature_min = df[... | def _calculate_two_way_communication(len_name, sampling_rate, upsampled, df):
# one-way statistics
| def get_statistical_features(df, criter, feature_name,name_pred):
feature_avg = df[criter][feature_name].mean()
feature_avg = -1 if pd.isnull(feature_avg) else feature_avg
feature_min = df[criter][feature_name].min()
feature_min = -1 if pd.isnull(feature_min) else feature_min
... | _statistics, pkt_tuple, row, protocol, len_name)
else:
update_statistics(pcap_statistics, pkt_tuple, row, protocol, len_name)
pcap_statistics = {}
tqdm.pandas(desc='{protocol} flow, flow byte limit->{flow_byte_limit}'.format(protocol=protocol, flow_byte_limit=max_byte_per_flow))
pcap_df.... | 141 | 141 | 473 | 25 | 115 | nyu-tandon-hsn-ai/tcp-trace-feature-selection | python/flow_feature.py | Python | _calculate_two_way_communication | _calculate_two_way_communication | 129 | 160 | 129 | 130 | d3bc0a8163a035837f089bb212b316a12a3fb236 | bigcode/the-stack | train |
4341ecda0e9dc72a98ad27f6 | train | function | @pytest.fixture
def event_bus_name():
"""
Event Bus name
"""
return get_parameter("/ecommerce/{Environment}/platform/event-bus/name")
| @pytest.fixture
def event_bus_name():
| """
Event Bus name
"""
return get_parameter("/ecommerce/{Environment}/platform/event-bus/name")
| # pylint: disable=import-error
from helpers import get_parameter # pylint: disable=import-error,no-name-in-module
@pytest.fixture
def table_name():
"""
DynamoDB table name
"""
return get_parameter("/ecommerce/{Environment}/orders/table/name")
@pytest.fixture
def event_bus_name():
| 64 | 64 | 33 | 8 | 56 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | event_bus_name | event_bus_name | 20 | 26 | 20 | 21 | c02b6fe05eda59624d2f99486db302897d852211 | bigcode/the-stack | train |
fffe876d75aaf58eec155fdb | train | function | def test_on_delivery_completed(order, listener, table_name, event_bus_name):
"""
Test OnEvents function on a DeliveryCompleted event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
tab... | def test_on_delivery_completed(order, listener, table_name, event_bus_name):
| """
Test OnEvents function on a DeliveryCompleted event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put_item(Item=order)
# Create the event
event = {
"Time":... | json.loads(message["Body"])
if order["orderId"] in body["resources"] and body["detail-type"] == "OrderModified":
found = True
assert "status" in body["detail"]["changed"]
assert body["detail"]["new"]["status"] == "PACKAGING_FAILED"
assert found == True
# Clean up
... | 104 | 104 | 348 | 16 | 88 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | test_on_delivery_completed | test_on_delivery_completed | 182 | 226 | 182 | 182 | 070fda5ff8cd879213bfc60d99a7cccd51d9b8a1 | bigcode/the-stack | train |
c618567936d90ee0a957fe43 | train | function | @pytest.fixture(scope="function")
def order(get_order):
return get_order()
| @pytest.fixture(scope="function")
def order(get_order):
| return get_order()
| DB table name
"""
return get_parameter("/ecommerce/{Environment}/orders/table/name")
@pytest.fixture
def event_bus_name():
"""
Event Bus name
"""
return get_parameter("/ecommerce/{Environment}/platform/event-bus/name")
@pytest.fixture(scope="function")
def order(get_order):
| 64 | 64 | 16 | 11 | 53 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | order | order | 29 | 31 | 29 | 30 | 3de83f7012d674aea6d3ad49b880e71283646f7d | bigcode/the-stack | train |
70356e38eefb93677e9764fb | train | function | def test_on_delivery_failed(order, listener, table_name, event_bus_name):
"""
Test OnEvents function on a DeliveryFailed event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put... | def test_on_delivery_failed(order, listener, table_name, event_bus_name):
| """
Test OnEvents function on a DeliveryFailed event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put_item(Item=order)
# Create the event
event = {
"Time": da... | json.loads(message["Body"])
if order["orderId"] in body["resources"] and body["detail-type"] == "OrderModified":
found = True
assert "status" in body["detail"]["changed"]
assert body["detail"]["new"]["status"] == "FULFILLED"
assert found == True
# Clean up
table... | 104 | 104 | 348 | 16 | 88 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | test_on_delivery_failed | test_on_delivery_failed | 229 | 273 | 229 | 229 | 917ede76be9dd6881bdc99c06e2354715635e3f4 | bigcode/the-stack | train |
07efa66aa057861c74a466c4 | train | function | @pytest.fixture
def table_name():
"""
DynamoDB table name
"""
return get_parameter("/ecommerce/{Environment}/orders/table/name")
| @pytest.fixture
def table_name():
| """
DynamoDB table name
"""
return get_parameter("/ecommerce/{Environment}/orders/table/name")
| import copy
import datetime
import json
import time
import boto3
import pytest
from fixtures import listener, get_order, get_product # pylint: disable=import-error
from helpers import get_parameter # pylint: disable=import-error,no-name-in-module
@pytest.fixture
def table_name():
| 61 | 64 | 31 | 7 | 53 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | table_name | table_name | 11 | 17 | 11 | 12 | 81949913cabc09a0afff06189cdbd4e9a8567dd9 | bigcode/the-stack | train |
efd98e3c4961460956e93bf2 | train | function | def test_on_package_created_products(order, listener, table_name, event_bus_name):
"""
Test OnEvents function on a PackageCreated event when there are less products
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store... | def test_on_package_created_products(order, listener, table_name, event_bus_name):
| """
Test OnEvents function on a PackageCreated event when there are less products
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put_item(Item=order)
package_order = copy.d... | print("MESSAGE RECEIVED:", message)
body = json.loads(message["Body"])
if order["orderId"] in body["resources"] and body["detail-type"] == "OrderModified":
found = True
assert "status" in body["detail"]["changed"]
assert "products" not in body["detail"]["changed"]
... | 128 | 128 | 429 | 17 | 111 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | test_on_package_created_products | test_on_package_created_products | 82 | 132 | 82 | 82 | 48c90d9d3f23cafb653b0edc2440a0a97ee55817 | bigcode/the-stack | train |
26045f61553e00c731a61a8f | train | function | def test_on_packaging_failed(order, listener, table_name, event_bus_name):
"""
Test OnEvents function on a PackagingFailed event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.p... | def test_on_packaging_failed(order, listener, table_name, event_bus_name):
| """
Test OnEvents function on a PackagingFailed event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put_item(Item=order)
# Create the event
event = {
"Time": d... | Id"] in body["resources"] and body["detail-type"] == "OrderModified":
found = True
assert "status" in body["detail"]["changed"]
assert "products" in body["detail"]["changed"]
assert body["detail"]["new"]["status"] == "PACKAGED"
assert found == True
# Clean up
... | 105 | 105 | 350 | 17 | 88 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | test_on_packaging_failed | test_on_packaging_failed | 135 | 179 | 135 | 135 | 7e0934248624de52badf2dc6a773c7009b97255f | bigcode/the-stack | train |
f9304dcb3e582b130a37cb81 | train | function | def test_on_package_created(order, listener, table_name, event_bus_name):
"""
Test OnEvents function on a PackageCreated event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put... | def test_on_package_created(order, listener, table_name, event_bus_name):
| """
Test OnEvents function on a PackageCreated event
"""
eventbridge = boto3.client("events")
table = boto3.resource("dynamodb").Table(table_name) # pylint: disable=no-member
# Store order in DynamoDB table
table.put_item(Item=order)
# Create the event
event = {
"Time": da... | # pylint: disable=import-error,no-name-in-module
@pytest.fixture
def table_name():
"""
DynamoDB table name
"""
return get_parameter("/ecommerce/{Environment}/orders/table/name")
@pytest.fixture
def event_bus_name():
"""
Event Bus name
"""
return get_parameter("/ecommerce/{Environm... | 108 | 108 | 360 | 16 | 92 | perufork/aws-serverless-ecommerce-platform | orders/tests/integ/test_on_events.py | Python | test_on_package_created | test_on_package_created | 34 | 79 | 34 | 34 | 5096d85689877d397529716efcf2faa807b8f276 | bigcode/the-stack | train |
2bcfed6facca201ebd6f9cb4 | train | class | @log.class_logger
class ColumnProperty(StrategizedProperty):
"""Describes an object attribute that corresponds to a table column.
Public constructor is the :func:`_orm.column_property` function.
"""
strategy_wildcard_key = "column"
inherit_cache = True
_links_to_entity = False
__slots__ ... | @log.class_logger
class ColumnProperty(StrategizedProperty):
| """Describes an object attribute that corresponds to a table column.
Public constructor is the :func:`_orm.column_property` function.
"""
strategy_wildcard_key = "column"
inherit_cache = True
_links_to_entity = False
__slots__ = (
"_orig_columns",
"columns",
"grou... | # orm/properties.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""MapperProperty implementations.
This is a private module which defines the be... | 215 | 256 | 2,801 | 13 | 202 | immerrr/sqlalchemy | lib/sqlalchemy/orm/properties.py | Python | ColumnProperty | ColumnProperty | 38 | 437 | 38 | 39 | 1f536ff9acd3bfe1711dcc34eab7b56b3a6dc913 | bigcode/the-stack | train |
494c2e3ea8fb4e16619853db | train | function | @frappe.whitelist(allow_guest=True)
def create_insurance_policy_template(json_dict):
if json_dict:
try:
ipt_doc = frappe.new_doc("Insurance Policy Template")
ipt_doc.data = json_dict
ipt_doc.save()
frappe.db.commit()
return ipt_doc.name
except Exception as e:
print(e) | @frappe.whitelist(allow_guest=True)
def create_insurance_policy_template(json_dict):
| if json_dict:
try:
ipt_doc = frappe.new_doc("Insurance Policy Template")
ipt_doc.data = json_dict
ipt_doc.save()
frappe.db.commit()
return ipt_doc.name
except Exception as e:
print(e) | response._content
json_dict = json.dumps(xmltodict.parse(response_data))
ipt_name = create_insurance_policy_template(json_dict)
return ipt_name
except Exception as e:
print(e)
@frappe.whitelist(allow_guest=True)
def create_insurance_policy_template(json_dict):
| 64 | 64 | 77 | 19 | 45 | jsukrut/InsurancePolicy | insurancepolicy/api/api.py | Python | create_insurance_policy_template | create_insurance_policy_template | 23 | 33 | 23 | 24 | 86194870e7dac367d0b523840211daf503f530f5 | bigcode/the-stack | train |
2dfec98d17354d7cd0054c93 | train | function | @frappe.whitelist(allow_guest=True)
def sync_daily_xml():
url ='https://ratingqa.itcdataservices.com/Webservices/ITCRateEngineAPI/api/objectsamples/ITCRateEngineRequest?type=xml&useacord=true'
try:
response = requests.get(url)
if response.status_code == 200:
# print(response)
response_data = response._conte... | @frappe.whitelist(allow_guest=True)
def sync_daily_xml():
| url ='https://ratingqa.itcdataservices.com/Webservices/ITCRateEngineAPI/api/objectsamples/ITCRateEngineRequest?type=xml&useacord=true'
try:
response = requests.get(url)
if response.status_code == 200:
# print(response)
response_data = response._content
json_dict = json.dumps(xmltodict.parse(response_data... | import frappe
import xmltodict
import json
import requests
@frappe.whitelist(allow_guest=True)
def sync_daily_xml():
| 29 | 64 | 127 | 15 | 13 | jsukrut/InsurancePolicy | insurancepolicy/api/api.py | Python | sync_daily_xml | sync_daily_xml | 9 | 21 | 9 | 10 | a190b3c3b54a1326322be3105e3101598cc0adda | bigcode/the-stack | train |
976c9599bdf2bb0519e3238b | train | class | class AuthFormTest(TestCase):
def setUp(self):
try:
alice = self.create_user('alice', 'password')
except IntegrityError:
self.skipTest("Failed to create user.")
else:
alice.emaildevice_set.create()
if not hasattr(alice, 'email'):
self.... | class AuthFormTest(TestCase):
| def setUp(self):
try:
alice = self.create_user('alice', 'password')
except IntegrityError:
self.skipTest("Failed to create user.")
else:
alice.emaildevice_set.create()
if not hasattr(alice, 'email'):
self.skipTest("User model has no em... | from django.db import IntegrityError
from django.core import mail
from django_otp.forms import OTPAuthenticationForm
from django_otp.tests import TestCase
from .models import EmailDevice
class AuthFormTest(TestCase):
| 46 | 76 | 256 | 7 | 38 | robintema/django-otp | django_otp/plugins/otp_email/tests.py | Python | AuthFormTest | AuthFormTest | 9 | 42 | 9 | 9 | c0de1ab6c3b8d6b8e24a4f95a5d9419fd82db891 | bigcode/the-stack | train |
e02da4b1060d6c36875a2657 | train | class | class TestHeap(TestCase):
def testMaxHeapifyOne(self):
aList = [2]
maxHeapify(aList, 0)
self.assertEquals(aList, [2])
def testMaxHeapifyThree(self):
aList = [2, 4, 3]
maxHeapify(aList, 0)
self.assertEquals(aList, [4, 2, 3])
def testBuildMaxHeap(self):
... | class TestHeap(TestCase):
| def testMaxHeapifyOne(self):
aList = [2]
maxHeapify(aList, 0)
self.assertEquals(aList, [2])
def testMaxHeapifyThree(self):
aList = [2, 4, 3]
maxHeapify(aList, 0)
self.assertEquals(aList, [4, 2, 3])
def testBuildMaxHeap(self):
aList = [2, 4, 3]
... | from unittest import main, TestCase
from heap import *
class TestHeap(TestCase):
| 18 | 145 | 484 | 6 | 12 | ethankennerly/intro-algorithms | testHeap.py | Python | TestHeap | TestHeap | 6 | 55 | 6 | 6 | b6cc625c71529cdf0b38f11cf2cd230a3839d6ce | bigcode/the-stack | train |
32365c461a5594c657f7cbe9 | train | class | class CT_NumDataSource(BaseOxmlElement):
"""
``<c:yVal>`` custom element class used in XY and bubble charts, and
perhaps others.
"""
numRef = OneAndOnlyOne('c:numRef')
@property
def ptCount_val(self):
"""
Return the value of `./c:numRef/c:numCache/c:ptCount/@val`,
sp... | class CT_NumDataSource(BaseOxmlElement):
| """
``<c:yVal>`` custom element class used in XY and bubble charts, and
perhaps others.
"""
numRef = OneAndOnlyOne('c:numRef')
@property
def ptCount_val(self):
"""
Return the value of `./c:numRef/c:numCache/c:ptCount/@val`,
specifying how many `c:pt` elements are in ... | @classmethod
def new_dPt(cls):
"""
Return a newly created "loose" `c:dPt` element containing its default
subtree.
"""
dPt = OxmlElement('c:dPt')
dPt.append(OxmlElement('c:idx'))
return dPt
class CT_NumDataSource(BaseOxmlElement):
| 75 | 75 | 251 | 10 | 64 | CAVOK-IT/python-pptx | pptx/oxml/chart/series.py | Python | CT_NumDataSource | CT_NumDataSource | 41 | 66 | 41 | 41 | 77f42193b11085875e9d9f6ee5bb9af6c564e77f | bigcode/the-stack | train |
952c111c921afd588eb59225 | train | class | class CT_DPt(BaseOxmlElement):
"""
``<c:dPt>`` custom element class, containing visual properties for a data
point.
"""
_tag_seq = (
'c:idx', 'c:invertIfNegative', 'c:marker', 'c:bubble3D',
'c:explosion', 'c:spPr', 'c:pictureOptions', 'c:extLst'
)
idx = OneAndOnlyOne('c:idx')... | class CT_DPt(BaseOxmlElement):
| """
``<c:dPt>`` custom element class, containing visual properties for a data
point.
"""
_tag_seq = (
'c:idx', 'c:invertIfNegative', 'c:marker', 'c:bubble3D',
'c:explosion', 'c:spPr', 'c:pictureOptions', 'c:extLst'
)
idx = OneAndOnlyOne('c:idx')
marker = ZeroOrOne('c:mark... | __ import absolute_import, print_function, unicode_literals
from ..simpletypes import XsdUnsignedInt
from ..xmlchemy import (
BaseOxmlElement, OneAndOnlyOne, OxmlElement, RequiredAttribute,
ZeroOrMore, ZeroOrOne
)
class CT_DPt(BaseOxmlElement):
| 64 | 64 | 215 | 9 | 55 | CAVOK-IT/python-pptx | pptx/oxml/chart/series.py | Python | CT_DPt | CT_DPt | 16 | 38 | 16 | 16 | 343eef35a23b4e248678aac25eba57018d448353 | bigcode/the-stack | train |
b2e3ca158449abacee0d871a | train | class | class CT_StrVal_NumVal_Composite(BaseOxmlElement):
"""
``<c:pt>`` element, can be either CT_StrVal or CT_NumVal complex type.
Using this class for both, differentiating as needed.
"""
v = OneAndOnlyOne('c:v')
idx = RequiredAttribute('idx', XsdUnsignedInt)
@property
def value(self):
... | class CT_StrVal_NumVal_Composite(BaseOxmlElement):
| """
``<c:pt>`` element, can be either CT_StrVal or CT_NumVal complex type.
Using this class for both, differentiating as needed.
"""
v = OneAndOnlyOne('c:v')
idx = RequiredAttribute('idx', XsdUnsignedInt)
@property
def value(self):
"""
The float value of the text in the ... | 0
return int(vals[0])
def _new_dPt(self):
"""
Overrides the metaclass generated method to get `c:dPt` with minimal
subtree.
"""
return CT_DPt.new_dPt()
class CT_StrVal_NumVal_Composite(BaseOxmlElement):
| 64 | 64 | 114 | 13 | 51 | CAVOK-IT/python-pptx | pptx/oxml/chart/series.py | Python | CT_StrVal_NumVal_Composite | CT_StrVal_NumVal_Composite | 183 | 196 | 183 | 183 | 823f668d2ff07a350e25bab4e1ff8cd181e64d16 | bigcode/the-stack | train |
17293643884eaabe707d5375 | train | class | class CT_SeriesComposite(BaseOxmlElement):
"""
``<c:ser>`` custom element class. Note there are several different series
element types in the schema, such as ``CT_LineSer`` and ``CT_BarSer``,
but they all share the same tag name. This class acts as a composite and
depends on the caller not to do any... | class CT_SeriesComposite(BaseOxmlElement):
| """
``<c:ser>`` custom element class. Note there are several different series
element types in the schema, such as ``CT_LineSer`` and ``CT_BarSer``,
but they all share the same tag name. This class acts as a composite and
depends on the caller not to do anything invalid for a series belonging
to... | (BaseOxmlElement):
"""
``<c:yVal>`` custom element class used in XY and bubble charts, and
perhaps others.
"""
numRef = OneAndOnlyOne('c:numRef')
@property
def ptCount_val(self):
"""
Return the value of `./c:numRef/c:numCache/c:ptCount/@val`,
specifying how many `c:p... | 256 | 256 | 1,130 | 10 | 245 | CAVOK-IT/python-pptx | pptx/oxml/chart/series.py | Python | CT_SeriesComposite | CT_SeriesComposite | 69 | 180 | 69 | 69 | 173afb306f0183d3174dfc89c5076f03870838a9 | bigcode/the-stack | train |
c5620630bfa17024c6a53d56 | train | class | @skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresDeleteClusterTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
self.cmd_run_all_mock = Mock(return_value={'stdout': LSCLUSTER})
self.addCleanup(delattr, self, 'cmd_run_all_mock')
patcher = patch('salt.utils.path.which',... | @skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresDeleteClusterTestCase(TestCase, LoaderModuleMockMixin):
| def setup_loader_modules(self):
self.cmd_run_all_mock = Mock(return_value={'stdout': LSCLUSTER})
self.addCleanup(delattr, self, 'cmd_run_all_mock')
patcher = patch('salt.utils.path.which', Mock(return_value='/usr/bin/pg_dropcluster'))
patcher.start()
self.addCleanup(patcher.s... | _exists('8.4') is True)
self.assertTrue(deb_postgres.cluster_exists('8.4', 'main') is True)
self.assertFalse(deb_postgres.cluster_exists('3.4', 'main'))
@skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresDeleteClusterTestCase(TestCase, LoaderModuleMockMixin):
| 75 | 76 | 256 | 27 | 48 | jubrad/salt | tests/unit/modules/test_deb_postgres.py | Python | PostgresDeleteClusterTestCase | PostgresDeleteClusterTestCase | 124 | 150 | 124 | 126 | f449dba399f82817c56a0a4a32fa1e9849952b73 | bigcode/the-stack | train |
7a7b3750abe81618d2db1fc3 | train | class | @skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresClusterTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
self.cmd_run_all_mock = Mock(return_value={'stdout': LSCLUSTER})
self.addCleanup(delattr, self, 'cmd_run_all_mock')
patcher = patch('salt.utils.path.which', Mock(... | @skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresClusterTestCase(TestCase, LoaderModuleMockMixin):
| def setup_loader_modules(self):
self.cmd_run_all_mock = Mock(return_value={'stdout': LSCLUSTER})
self.addCleanup(delattr, self, 'cmd_run_all_mock')
patcher = patch('salt.utils.path.which', Mock(return_value='/usr/bin/pg_createcluster'))
patcher.start()
self.addCleanup(patcher... | srv/8.4/main \
/var/log/postgresql/postgresql-8.4-main.log
9.1 main 5433 online postgres /srv/9.1/main \
/var/log/postgresql/postgresql-9.1-main.log
'''
@skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresClusterTestCase(TestCase, LoaderModuleMockMixin):
| 81 | 82 | 274 | 26 | 55 | jubrad/salt | tests/unit/modules/test_deb_postgres.py | Python | PostgresClusterTestCase | PostgresClusterTestCase | 23 | 56 | 23 | 25 | 88ec5f84c6458fa8120732f0cf6a4e0daf45f447 | bigcode/the-stack | train |
b3c5d529f69564a9f9aa68bc | train | class | @skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresLsClusterTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
self.cmd_run_all_mock = Mock(return_value={'stdout': LSCLUSTER})
self.addCleanup(delattr, self, 'cmd_run_all_mock')
patcher = patch('salt.utils.path.which', Moc... | @skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresLsClusterTestCase(TestCase, LoaderModuleMockMixin):
| def setup_loader_modules(self):
self.cmd_run_all_mock = Mock(return_value={'stdout': LSCLUSTER})
self.addCleanup(delattr, self, 'cmd_run_all_mock')
patcher = patch('salt.utils.path.which', Mock(return_value='/usr/bin/pg_lsclusters'))
patcher.start()
self.addCleanup(patcher.st... | datadir /opt/postgresql ' \
'9.3 main'
self.assertEqual(cmdstr, self.cmd_run_all_mock.call_args[0][0])
# XXX version should be a string but from cmdline you get a float
# def test_cluster_create_with_float(self):
# self.assertRaises(AssertionError, deb_postgres.cluster_create,
#... | 151 | 152 | 509 | 27 | 124 | jubrad/salt | tests/unit/modules/test_deb_postgres.py | Python | PostgresLsClusterTestCase | PostgresLsClusterTestCase | 68 | 121 | 68 | 70 | 888c4fa5d19b1b9d68bb01c7d949c62ace1d1cb2 | bigcode/the-stack | train |
717cd326108b131bf9651c1f | train | function | def process_request(url, method, headers, payload):
r = urlreq(url, verb=method, params=payload, verify=False, headers=headers)
if r.ok:
print("Request was successful")
print("Status Code: {}".format(r))
else:
print("Request failed")
print("Status Code: {}".format(r))
... | def process_request(url, method, headers, payload):
| r = urlreq(url, verb=method, params=payload, verify=False, headers=headers)
if r.ok:
print("Request was successful")
print("Status Code: {}".format(r))
else:
print("Request failed")
print("Status Code: {}".format(r))
#print("Headers: {}".format(headers))
#prin... | = "@@{vc.secret}@@"
api_server = "@@{vc_endpoint}@@"
datacenter = "@@{vc_datacenter}@@"
vm_folder_name = "@@{calm_application_name}@@"
#endregion
#region API call function
def process_request(url, method, headers, payload):
| 64 | 64 | 158 | 11 | 52 | mlavi/blueprints | task-library/vsphere/VcSoapGetVmFolder.py | Python | process_request | process_request | 20 | 38 | 20 | 20 | c405f194e01c975361f4c8117eedb5f0c528e69d | bigcode/the-stack | train |
802fff2a35c26dccf4b1a0bf | train | class | class GetFlattenedExecutorTestCase(TestCase):
def setUp(self):
class TestEngine(QueryExecutorBaseClass):
@classmethod
def EXECUTOR_LANGUAGE(cls):
return "English"
@classmethod
def EXECUTOR_NAME(cls):
return "Test"
... | class GetFlattenedExecutorTestCase(TestCase):
| def setUp(self):
class TestEngine(QueryExecutorBaseClass):
@classmethod
def EXECUTOR_LANGUAGE(cls):
return "English"
@classmethod
def EXECUTOR_NAME(cls):
return "Test"
@classmethod
def EXECUTOR_TEMPLATE... | from unittest import TestCase, mock
from lib.query_executor.base_executor import QueryExecutorBaseClass
from lib.query_executor import all_executors
class GetFlattenedExecutorTestCase(TestCase):
| 40 | 86 | 287 | 10 | 29 | shivammmmm/querybook | querybook/tests/test_lib/test_query_executor/test_all_executors.py | Python | GetFlattenedExecutorTestCase | GetFlattenedExecutorTestCase | 6 | 48 | 6 | 6 | 89a91f6b528d5a6bae3e866c02d9e3704678ae06 | bigcode/the-stack | train |
510b9365863a6f75e56c9b3c | train | class | class GetExecutorClassTestCase(TestCase):
def setUp(self):
class TestEngine(QueryExecutorBaseClass):
@classmethod
def EXECUTOR_LANGUAGE(cls):
return "English"
@classmethod
def EXECUTOR_NAME(cls):
return "Test"
@cla... | class GetExecutorClassTestCase(TestCase):
| def setUp(self):
class TestEngine(QueryExecutorBaseClass):
@classmethod
def EXECUTOR_LANGUAGE(cls):
return "English"
@classmethod
def EXECUTOR_NAME(cls):
return "Test"
@classmethod
def EXECUTOR_TEMPLATE... | "English", "name": "Test", "template": None},
{"language": "English", "name": "Test2", "template": None},
{"language": "French", "name": "Test2", "template": None},
{"language": "Spanish", "name": "Test2", "template": None},
],
)
c... | 84 | 84 | 280 | 9 | 75 | shivammmmm/querybook | querybook/tests/test_lib/test_query_executor/test_all_executors.py | Python | GetExecutorClassTestCase | GetExecutorClassTestCase | 51 | 94 | 51 | 51 | ea933485c41520e684156bfd96c40d4ad17e40bf | bigcode/the-stack | train |
6fed710b53beaf8dad7aff78 | train | class | class TestCursos:
headers = {
'Authorization': 'Token 22c4f0770323557ee4d67258c66e9df5d7660fde'
}
BASE_URL = 'http://localhost:8000/api/v2/'
def test_get_cursos(self):
response = requests.get(f'{self.BASE_URL}cursos', headers=self.headers)
assert response.status_code == 200, f'... | class TestCursos:
| headers = {
'Authorization': 'Token 22c4f0770323557ee4d67258c66e9df5d7660fde'
}
BASE_URL = 'http://localhost:8000/api/v2/'
def test_get_cursos(self):
response = requests.get(f'{self.BASE_URL}cursos', headers=self.headers)
assert response.status_code == 200, f'{response.status_c... | import requests
class TestCursos:
| 7 | 154 | 515 | 4 | 2 | stevillis/gu-escola | teste_pytest.py | Python | TestCursos | TestCursos | 4 | 52 | 4 | 4 | 1b10c36f25b68f9312e341d339454aab3e830750 | bigcode/the-stack | train |
3f593cede51c137138b74d95 | train | class | class DistGraphServer(KVServer):
''' The DistGraph server.
This DistGraph server loads the graph data and sets up a service so that trainers and
samplers can read data of a graph partition (graph structure, node data and edge data)
from remote machines. A server is responsible for one graph partition.
... | class DistGraphServer(KVServer):
| ''' The DistGraph server.
This DistGraph server loads the graph data and sets up a service so that trainers and
samplers can read data of a graph partition (graph structure, node data and edge data)
from remote machines. A server is responsible for one graph partition.
Currently, each machine runs... | , _ = g._client.get_data_meta(str(name))
# We create a wrapper on the existing tensor in the kvstore.
self._data[name.get_name()] = DistTensor(shape, dtype, name.get_name(),
part_policy=policy)
def _get_names(self):
return list(se... | 256 | 256 | 940 | 8 | 248 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | DistGraphServer | DistGraphServer | 264 | 356 | 264 | 264 | 322a7f5a2ceefcefdf0f003c5838000674f8850e | bigcode/the-stack | train |
2015fee38813b33b93c224ed | train | function | def _split_even(partition_book, rank, elements):
''' Split the input element list evenly.
'''
num_clients = role.get_num_trainers()
num_client_per_part = num_clients // partition_book.num_partitions()
# all ranks of the clients in the same machine are in a contiguous range.
if rank is None:
... | def _split_even(partition_book, rank, elements):
| ''' Split the input element list evenly.
'''
num_clients = role.get_num_trainers()
num_client_per_part = num_clients // partition_book.num_partitions()
# all ranks of the clients in the same machine are in a contiguous range.
if rank is None:
rank = role.get_trainer_rank()
assert ran... | client_id_in_part = rank % num_client_per_part
local_eles = _get_overlap(elements, local_eles)
# get a subset for the local client.
size = len(local_eles) // num_client_per_part
# if this isn't the last client in the partition.
if client_id_in_part + 1 < num_client_per_part:
return loc... | 132 | 132 | 440 | 12 | 120 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _split_even | _split_even | 1,066 | 1,109 | 1,066 | 1,066 | fdb11c430c24158a35f9e81d001e0fc735b25cc5 | bigcode/the-stack | train |
2fac990d41682e52f2e880ed | train | class | class InitGraphResponse(rpc.Response):
""" Ack the init graph request
"""
def __init__(self, graph_name):
self._graph_name = graph_name
def __getstate__(self):
return self._graph_name
def __setstate__(self, state):
self._graph_name = state
| class InitGraphResponse(rpc.Response):
| """ Ack the init graph request
"""
def __init__(self, graph_name):
self._graph_name = graph_name
def __getstate__(self):
return self._graph_name
def __setstate__(self, state):
self._graph_name = state
| __(self, state):
self._graph_name = state
def process_request(self, server_state):
if server_state.graph is None:
server_state.graph = _get_graph_from_shared_mem(self._graph_name)
return InitGraphResponse(self._graph_name)
class InitGraphResponse(rpc.Response):
| 64 | 64 | 70 | 8 | 56 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | InitGraphResponse | InitGraphResponse | 53 | 63 | 53 | 53 | 6b7da553f97e697ae59f8817c3ab00d94a65bf9e | bigcode/the-stack | train |
b6243d8cbf7479c4bc899ca8 | train | class | class HeteroNodeView(object):
"""A NodeView class to act as G.nodes for a DistGraph."""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
assert isinstance(key, str)
return NodeSpace(data=NodeDataView(self._graph, key))
| class HeteroNodeView(object):
| """A NodeView class to act as G.nodes for a DistGraph."""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
assert isinstance(key, str)
return NodeSpace(data=NodeDataView(self._graph, key))
| _name, 'inner_edge')
g.edata[EID] = _get_shared_mem_edata(g, graph_name, EID)
return g
NodeSpace = namedtuple('NodeSpace', ['data'])
EdgeSpace = namedtuple('EdgeSpace', ['data'])
class HeteroNodeView(object):
| 64 | 64 | 80 | 8 | 56 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | HeteroNodeView | HeteroNodeView | 133 | 142 | 133 | 133 | 8f98a6e583ee80414aa1bc85796673b515331b1d | bigcode/the-stack | train |
ac7069b09d221b4b8bdb5854 | train | class | class InitGraphRequest(rpc.Request):
""" Init graph on the backup servers.
When the backup server starts, they don't load the graph structure.
This request tells the backup servers that they can map to the graph structure
with shared memory.
"""
def __init__(self, graph_name):
self._gra... | class InitGraphRequest(rpc.Request):
| """ Init graph on the backup servers.
When the backup server starts, they don't load the graph structure.
This request tells the backup servers that they can map to the graph structure
with shared memory.
"""
def __init__(self, graph_name):
self._graph_name = graph_name
def __getst... |
from .graph_services import find_edges as dist_find_edges
from .graph_services import out_degrees as dist_out_degrees
from .graph_services import in_degrees as dist_in_degrees
from .dist_tensor import DistTensor
INIT_GRAPH = 800001
class InitGraphRequest(rpc.Request):
| 64 | 64 | 149 | 8 | 55 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | InitGraphRequest | InitGraphRequest | 32 | 51 | 32 | 32 | 724f89f4d9523e114dc094bffdb06aeb2167815f | bigcode/the-stack | train |
38633e9c46ed3dcc5589a88d | train | function | def _split_local(partition_book, rank, elements, local_eles):
''' Split the input element list with respect to data locality.
'''
num_clients = role.get_num_trainers()
num_client_per_part = num_clients // partition_book.num_partitions()
if rank is None:
rank = role.get_trainer_rank()
ass... | def _split_local(partition_book, rank, elements, local_eles):
| ''' Split the input element list with respect to data locality.
'''
num_clients = role.get_num_trainers()
num_client_per_part = num_clients // partition_book.num_partitions()
if rank is None:
rank = role.get_trainer_rank()
assert rank < num_clients, \
'The input rank ({}) is ... | .
"""
if isinstance(mask_arr, DistTensor):
masks = mask_arr[ids]
return F.boolean_mask(ids, masks)
else:
masks = F.gather_row(F.tensor(mask_arr), ids)
return F.boolean_mask(ids, masks)
def _split_local(partition_book, rank, elements, local_eles):
| 71 | 71 | 237 | 16 | 55 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _split_local | _split_local | 1,045 | 1,064 | 1,045 | 1,045 | 556726be7b0fde23aa8f47b6f2e68b718d2b6da0 | bigcode/the-stack | train |
8a718e808188025ff7cb26c6 | train | function | def _get_overlap(mask_arr, ids):
""" Select the IDs given a boolean mask array.
The boolean mask array indicates all of the IDs to be selected. We want to
find the overlap between the IDs selected by the boolean mask array and
the ID array.
Parameters
----------
mask_arr : 1D tensor
... | def _get_overlap(mask_arr, ids):
| """ Select the IDs given a boolean mask array.
The boolean mask array indicates all of the IDs to be selected. We want to
find the overlap between the IDs selected by the boolean mask array and
the ID array.
Parameters
----------
mask_arr : 1D tensor
A boolean mask array.
ids :... | name = parse_hetero_data_name(name)
right_type = (name.get_type() == etype) if etype is not None else True
if name.is_edge() and right_type:
edata_names.append(name)
return edata_names
def _get_overlap(mask_arr, ids):
| 64 | 64 | 162 | 9 | 54 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _get_overlap | _get_overlap | 1,019 | 1,043 | 1,019 | 1,019 | b819566070b24b077ea76c028e75ca0f4089e445 | bigcode/the-stack | train |
bca4388384d4af17aed4e0d8 | train | function | def _get_graph_from_shared_mem(graph_name):
''' Get the graph from the DistGraph server.
The DistGraph server puts the graph structure of the local partition in the shared memory.
The client can access the graph structure and some metadata on nodes and edges directly
through shared memory to reduce the... | def _get_graph_from_shared_mem(graph_name):
| ''' Get the graph from the DistGraph server.
The DistGraph server puts the graph structure of the local partition in the shared memory.
The client can access the graph structure and some metadata on nodes and edges directly
through shared memory to reduce the overhead of data access.
'''
g, nty... | ]
dtype = DTYPE_DICT[dtype]
data = empty_shared_mem(_get_edata_path(graph_name, name), False, shape, dtype)
dlpack = data.to_dlpack()
return F.zerocopy_from_dlpack(dlpack)
def _get_graph_from_shared_mem(graph_name):
| 64 | 64 | 215 | 10 | 54 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _get_graph_from_shared_mem | _get_graph_from_shared_mem | 111 | 128 | 111 | 111 | 7b8ee46b4a25da7df3259a0d8a120d7f012ae222 | bigcode/the-stack | train |
cbdb4da1817692290531029e | train | function | def _get_shared_mem_ndata(g, graph_name, name):
''' Get shared-memory node data from DistGraph server.
This is called by the DistGraph client to access the node data in the DistGraph server
with shared memory.
'''
shape = (g.number_of_nodes(),)
dtype = FIELD_DICT[name]
dtype = DTYPE_DICT[dt... | def _get_shared_mem_ndata(g, graph_name, name):
| ''' Get shared-memory node data from DistGraph server.
This is called by the DistGraph client to access the node data in the DistGraph server
with shared memory.
'''
shape = (g.number_of_nodes(),)
dtype = FIELD_DICT[name]
dtype = DTYPE_DICT[dtype]
data = empty_shared_mem(_get_ndata_path... | ': F.int32, # A flag indicates whether the edge is inside a partition.
NID: F.int64,
EID: F.int64,
NTYPE: F.int16,
ETYPE: F.int16}
def _get_shared_mem_ndata(g, graph_name, name):
| 64 | 64 | 123 | 14 | 50 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _get_shared_mem_ndata | _get_shared_mem_ndata | 85 | 96 | 85 | 85 | 4a0c07a592bb1b31b6610d0a0edd27cd117a5002 | bigcode/the-stack | train |
1a31b87234756cf06e8ad6e4 | train | class | class EdgeDataView(MutableMapping):
"""The data view class when G.edges[...].data is called.
"""
__slots__ = ['_graph', '_data']
def __init__(self, g, etype=None):
self._graph = g
# When this is created, the server may already load edge data. We need to
# initialize the edge dat... | class EdgeDataView(MutableMapping):
| """The data view class when G.edges[...].data is called.
"""
__slots__ = ['_graph', '_data']
def __init__(self, g, etype=None):
self._graph = g
# When this is created, the server may already load edge data. We need to
# initialize the edge data in advance.
names = g._get... | len__(self):
# The number of node data may change. Let's count it every time we need them.
# It's not called frequently. It should be fine.
return len(self._data)
def __iter__(self):
return iter(self._data)
def __repr__(self):
reprs = {}
for name in self._data:
... | 132 | 132 | 440 | 8 | 124 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | EdgeDataView | EdgeDataView | 209 | 261 | 209 | 209 | 462efa96a1a0e9c618723db84a3f74e547e4d878 | bigcode/the-stack | train |
7224938714bab7ae8eb5ae48 | train | class | class HeteroEdgeView(object):
"""A NodeView class to act as G.nodes for a DistGraph."""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
assert isinstance(key, str)
return EdgeSpace(data=EdgeDataView(self._graph, key))
| class HeteroEdgeView(object):
| """A NodeView class to act as G.nodes for a DistGraph."""
__slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
assert isinstance(key, str)
return EdgeSpace(data=EdgeDataView(self._graph, key))
| __slots__ = ['_graph']
def __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
assert isinstance(key, str)
return NodeSpace(data=NodeDataView(self._graph, key))
class HeteroEdgeView(object):
| 64 | 64 | 80 | 8 | 56 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | HeteroEdgeView | HeteroEdgeView | 144 | 153 | 144 | 144 | 493275632d2eef4bade65fe4f774a89fec28e419 | bigcode/the-stack | train |
597346bc24dff92777664f10 | train | function | def node_split(nodes, partition_book=None, ntype='_N', rank=None, force_even=True):
''' Split nodes and return a subset for the local rank.
This function splits the input nodes based on the partition book and
returns a subset of nodes for the local rank. This method is used for
dividing workloads for d... | def node_split(nodes, partition_book=None, ntype='_N', rank=None, force_even=True):
| ''' Split nodes and return a subset for the local rank.
This function splits the input nodes based on the partition book and
returns a subset of nodes for the local rank. This method is used for
dividing workloads for distributed training.
The input nodes are stored as a vector of masks. The lengt... | # is 1.
part_size = len(eles) // num_clients
sizes = [part_size] * num_clients
remain = len(eles) - part_size * num_clients
if remain > 0:
for i in range(num_clients):
sizes[i] += 1
remain -= 1
if remain == 0:
break
offsets = np.cumsum(siz... | 158 | 159 | 532 | 21 | 137 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | node_split | node_split | 1,112 | 1,163 | 1,112 | 1,112 | cda4f7371a0182fb30ae3bb9c3933dd1878dcc53 | bigcode/the-stack | train |
790e2ef0187bc939d7feb35e | train | function | def _get_shared_mem_edata(g, graph_name, name):
''' Get shared-memory edge data from DistGraph server.
This is called by the DistGraph client to access the edge data in the DistGraph server
with shared memory.
'''
shape = (g.number_of_edges(),)
dtype = FIELD_DICT[name]
dtype = DTYPE_DICT[dt... | def _get_shared_mem_edata(g, graph_name, name):
| ''' Get shared-memory edge data from DistGraph server.
This is called by the DistGraph client to access the edge data in the DistGraph server
with shared memory.
'''
shape = (g.number_of_edges(),)
dtype = FIELD_DICT[name]
dtype = DTYPE_DICT[dtype]
data = empty_shared_mem(_get_edata_path... | DTYPE_DICT[dtype]
data = empty_shared_mem(_get_ndata_path(graph_name, name), False, shape, dtype)
dlpack = data.to_dlpack()
return F.zerocopy_from_dlpack(dlpack)
def _get_shared_mem_edata(g, graph_name, name):
| 64 | 64 | 123 | 14 | 50 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _get_shared_mem_edata | _get_shared_mem_edata | 98 | 109 | 98 | 98 | 60446cca71745ab7c25c04c4a8cf9c6fbb7f7568 | bigcode/the-stack | train |
94b0a4e1d71d3d117a3f7e88 | train | class | class DistGraph:
'''The class for accessing a distributed graph.
This class provides a subset of DGLGraph APIs for accessing partitioned graph data in
distributed GNN training and inference. Thus, its main use case is to work with
distributed sampling APIs to generate mini-batches and perform forward a... | class DistGraph:
| '''The class for accessing a distributed graph.
This class provides a subset of DGLGraph APIs for accessing partitioned graph data in
distributed GNN training and inference. Thus, its main use case is to work with
distributed sampling APIs to generate mini-batches and perform forward and
backward c... | + feature_name to avoid
# feature name collision for different node types.
ntype, feat_name = name.split('/')
data_name = HeteroDataName(True, ntype, feat_name)
self.init_data(name=str(data_name), policy_str=data_name.policy_str,
... | 256 | 256 | 4,879 | 4 | 252 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | DistGraph | DistGraph | 358 | 1,017 | 358 | 358 | e8b51cb5e99c17263a3c6a6b62fe7441c29bdae2 | bigcode/the-stack | train |
ad3c063bc010ed62c94cd8da | train | class | class NodeDataView(MutableMapping):
"""The data view class when dist_graph.ndata[...].data is called.
"""
__slots__ = ['_graph', '_data']
def __init__(self, g, ntype=None):
self._graph = g
# When this is created, the server may already load node data. We need to
# initialize the... | class NodeDataView(MutableMapping):
| """The data view class when dist_graph.ndata[...].data is called.
"""
__slots__ = ['_graph', '_data']
def __init__(self, g, ntype=None):
self._graph = g
# When this is created, the server may already load node data. We need to
# initialize the node data in advance.
names... | __init__(self, graph):
self._graph = graph
def __getitem__(self, key):
assert isinstance(key, str)
return NodeSpace(data=NodeDataView(self._graph, key))
class HeteroEdgeView(object):
"""A NodeView class to act as G.nodes for a DistGraph."""
__slots__ = ['_graph']
def __init__... | 133 | 133 | 444 | 8 | 125 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | NodeDataView | NodeDataView | 155 | 207 | 155 | 155 | b13ff5a7173838f8e4c542358632e37a72479603 | bigcode/the-stack | train |
2382797289b693fadbc14fde | train | function | def _copy_graph_to_shared_mem(g, graph_name, graph_format):
new_g = g.shared_memory(graph_name, formats=graph_format)
# We should share the node/edge data to the client explicitly instead of putting them
# in the KVStore because some of the node/edge data may be duplicated.
new_g.ndata['inner_node'] = _... | def _copy_graph_to_shared_mem(g, graph_name, graph_format):
| new_g = g.shared_memory(graph_name, formats=graph_format)
# We should share the node/edge data to the client explicitly instead of putting them
# in the KVStore because some of the node/edge data may be duplicated.
new_g.ndata['inner_node'] = _to_shared_mem(g.ndata['inner_node'],
... | init__(self, graph_name):
self._graph_name = graph_name
def __getstate__(self):
return self._graph_name
def __setstate__(self, state):
self._graph_name = state
def _copy_graph_to_shared_mem(g, graph_name, graph_format):
| 64 | 64 | 200 | 15 | 48 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | _copy_graph_to_shared_mem | _copy_graph_to_shared_mem | 65 | 76 | 65 | 65 | c0da04934f6ced2410aff22ada952fcfc67fc197 | bigcode/the-stack | train |
3a0cb7fb934d947ae3081684 | train | function | def edge_split(edges, partition_book=None, etype='_E', rank=None, force_even=True):
''' Split edges and return a subset for the local rank.
This function splits the input edges based on the partition book and
returns a subset of edges for the local rank. This method is used for
dividing workloads for d... | def edge_split(edges, partition_book=None, etype='_E', rank=None, force_even=True):
| ''' Split edges and return a subset for the local rank.
This function splits the input edges based on the partition book and
returns a subset of edges for the local rank. This method is used for
dividing workloads for distributed training.
The input edges can be stored as a vector of masks. The le... | (nodes, DistTensor):
assert partition_book is not None, 'Regular tensor requires a partition book.'
elif partition_book is None:
partition_book = nodes.part_policy.partition_book
assert len(nodes) == partition_book._num_nodes(ntype), \
'The length of boolean mask vector should be th... | 159 | 159 | 533 | 21 | 138 | alexpod1000/dgl | python/dgl/distributed/dist_graph.py | Python | edge_split | edge_split | 1,165 | 1,216 | 1,165 | 1,165 | 2b38bebe26a975e4007b6fc456777235e3dc6baf | bigcode/the-stack | train |
60bc803fcfbdcc2e9c071eb9 | train | function | def menu(coin: str, data: pd.DataFrame):
"""Prediction Techniques Menu"""
pred_controller = PredictionTechniquesController(coin, data)
pred_controller.call_help(None)
while True:
# Get input command from user
if session and gtff.USE_PROMPT_TOOLKIT:
completer = NestedComplet... | def menu(coin: str, data: pd.DataFrame):
| """Prediction Techniques Menu"""
pred_controller = PredictionTechniquesController(coin, data)
pred_controller.call_help(None)
while True:
# Get input command from user
if session and gtff.USE_PROMPT_TOOLKIT:
completer = NestedCompleter.from_nested_dict(
{c: ... | _view.display_mc_forecast(
data=self.data[self.target],
n_future=ns_parser.n_days,
n_sims=ns_parser.n_sims,
use_log=ns_parser.dist == "lognormal",
export=ns_parser.export,
time_res=self.resolution,
)
def menu(coin: str, data: pd.DataFrame):... | 74 | 74 | 247 | 13 | 61 | Aerex/GamestonkTerminal | gamestonk_terminal/cryptocurrency/prediction_techniques/pred_controller.py | Python | menu | menu | 811 | 846 | 811 | 811 | e84b6790dd2d55cda43a844a265788bae7950c2d | bigcode/the-stack | train |
e223e096f133e290a90e9fa5 | train | class | class PredictionTechniquesController:
"""Prediction Techniques Controller class"""
# Command choices
CHOICES = ["cls", "?", "help", "q", "quit", "load", "pick"]
CHOICES_MODELS = [
"ets",
"knn",
"regression",
"arima",
"mlp",
"rnn",
"lstm",
... | class PredictionTechniquesController:
| """Prediction Techniques Controller class"""
# Command choices
CHOICES = ["cls", "?", "help", "q", "quit", "load", "pick"]
CHOICES_MODELS = [
"ets",
"knn",
"regression",
"arima",
"mlp",
"rnn",
"lstm",
"conv1d",
"mc",
]
CHO... | """Crypto Prediction Controller"""
__docformat__ = "numpy"
import argparse
import difflib
from typing import List
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.h... | 194 | 256 | 5,066 | 6 | 187 | Aerex/GamestonkTerminal | gamestonk_terminal/cryptocurrency/prediction_techniques/pred_controller.py | Python | PredictionTechniquesController | PredictionTechniquesController | 37 | 808 | 37 | 37 | c03bb4eaf8e7ebcef5caf1a0ebcc255a1892be03 | bigcode/the-stack | train |
5cd9e1845d483a50c6ddb09a | train | class | class VisualizationsController(BaseAPIController, UsesVisualizationMixin, SharableMixin, UsesAnnotations):
"""
RESTful controller for interactions with visualizations.
"""
@expose_api
def index(self, trans, **kwargs):
"""
GET /api/visualizations:
"""
rval = []
... | class VisualizationsController(BaseAPIController, UsesVisualizationMixin, SharableMixin, UsesAnnotations):
| """
RESTful controller for interactions with visualizations.
"""
@expose_api
def index(self, trans, **kwargs):
"""
GET /api/visualizations:
"""
rval = []
user = trans.user
# TODO: search for: title, made by user, creation time range, type (vis name),... | """
Visualizations resource control over the API.
NOTE!: this is a work in progress and functionality and data structures
may change often.
"""
import json
import logging
from six import string_types
from galaxy import (
exceptions,
util,
web
)
from galaxy.model.item_attrs import UsesAnnotations
from gal... | 126 | 256 | 1,740 | 19 | 107 | uio-bmi/galaxy-graph-peak-caller | lib/galaxy/webapps/galaxy/api/visualizations.py | Python | VisualizationsController | VisualizationsController | 28 | 209 | 28 | 28 | 52ee604d33f5e65f08762325f845ba1cd2cdb4fd | bigcode/the-stack | train |
4a3fde573be69f5f2a5056f1 | train | function | def get_customer_tax_rate(request, product):
"""Returns the specfic customer tax for the current customer and product.
"""
cache_key = 'cached_customer_tax_rate_%s' % product.pk
if request and hasattr(request, cache_key):
return getattr(request, cache_key)
all_cache_key = u'all_customer_tax... | def get_customer_tax_rate(request, product):
| """Returns the specfic customer tax for the current customer and product.
"""
cache_key = 'cached_customer_tax_rate_%s' % product.pk
if request and hasattr(request, cache_key):
return getattr(request, cache_key)
all_cache_key = u'all_customer_taxes'
customer_taxes = cache.get(all_cache_... | # lfs imports
from django.core.cache import cache
from lfs.criteria.utils import get_first_valid
from lfs.customer_tax.models import CustomerTax
def get_customer_tax_rate(request, product):
| 41 | 64 | 174 | 9 | 31 | michael-hahn/django-lfs | lfs/customer_tax/utils.py | Python | get_customer_tax_rate | get_customer_tax_rate | 7 | 27 | 7 | 7 | d29def912744846d763676629ad054dd8ed4c2b0 | bigcode/the-stack | train |
48a93cf6386d0e4a25537ebb | train | function | def _calc_product_tax_rate(request, product):
try:
return product.get_product_tax_rate(request)
except AttributeError:
return 0.0
| def _calc_product_tax_rate(request, product):
| try:
return product.get_product_tax_rate(request)
except AttributeError:
return 0.0
| customer_taxes, product)
if customer_tax:
taxrate = customer_tax.rate
else:
taxrate = _calc_product_tax_rate(request, product)
if request:
setattr(request, cache_key, taxrate)
return taxrate
def _calc_product_tax_rate(request, product):
| 64 | 64 | 34 | 10 | 53 | michael-hahn/django-lfs | lfs/customer_tax/utils.py | Python | _calc_product_tax_rate | _calc_product_tax_rate | 30 | 34 | 30 | 30 | 32b97f5f749f81e22dd9e317fc6c447d04884e27 | bigcode/the-stack | train |
bd7fcc942f82130b6876ccd2 | train | class | class CNodeNoVersionIdle(CLazyNode):
def __init__(self):
super().__init__()
| class CNodeNoVersionIdle(CLazyNode):
| def __init__(self):
super().__init__()
| ()
for i in range(banscore):
self.send_message(msg_verack())
def on_reject(self, message): pass
# Node that never sends a version. This one just sits idle and hopes to receive
# any message (it shouldn't!)
class CNodeNoVersionIdle(CLazyNode):
| 64 | 64 | 22 | 10 | 54 | Kozisto/kabb30 | test/functional/p2p_leak.py | Python | CNodeNoVersionIdle | CNodeNoVersionIdle | 72 | 74 | 72 | 72 | 7c8141f258ecb311571a5ef108ffdc607fafa5ff | bigcode/the-stack | train |
a7b30f0bd7283d14be288ba5 | train | class | class CLazyNode(P2PInterface):
def __init__(self):
super().__init__()
self.unexpected_msg = False
self.ever_connected = False
def bad_message(self, message):
self.unexpected_msg = True
self.log.info("should not have received message: %s" % message.command)
def on_op... | class CLazyNode(P2PInterface):
| def __init__(self):
super().__init__()
self.unexpected_msg = False
self.ever_connected = False
def bad_message(self, message):
self.unexpected_msg = True
self.log.info("should not have received message: %s" % message.command)
def on_open(self):
self.ever_con... | to a node and sends it a few messages, trying to intice it
into sending us something it shouldn't.
Also test that nodes that send unsupported service bits to bitcoind are disconnected
and don't receive a VERACK. Unsupported service bits are currently 1 << 5 and
1 << 7 (until August 1st 2018)."""
from test_framework.... | 113 | 113 | 377 | 9 | 103 | Kozisto/kabb30 | test/functional/p2p_leak.py | Python | CLazyNode | CLazyNode | 23 | 56 | 23 | 23 | e8cc69fa16276753100214b7b816442ec5655084 | bigcode/the-stack | train |
8aa3a1ea2a3f306fa4b43b0c | train | class | class CNodeNoVersionBan(CLazyNode):
# send a bunch of veracks without sending a message. This should get us disconnected.
# NOTE: implementation-specific check here. Remove if bitcoind ban behavior changes
def on_open(self):
super().on_open()
for i in range(banscore):
self.send_m... | class CNodeNoVersionBan(CLazyNode):
# send a bunch of veracks without sending a message. This should get us disconnected.
# NOTE: implementation-specific check here. Remove if bitcoind ban behavior changes
| def on_open(self):
super().on_open()
for i in range(banscore):
self.send_message(msg_verack())
def on_reject(self, message): pass
| use this to send a bunch of messages
# anyway, and eventually get disconnected.
class CNodeNoVersionBan(CLazyNode):
# send a bunch of veracks without sending a message. This should get us disconnected.
# NOTE: implementation-specific check here. Remove if bitcoind ban behavior changes
| 64 | 64 | 87 | 47 | 17 | Kozisto/kabb30 | test/functional/p2p_leak.py | Python | CNodeNoVersionBan | CNodeNoVersionBan | 60 | 68 | 60 | 62 | b64aac6db82461262003ed4f7652f68f216ba1b4 | bigcode/the-stack | train |
9537606f07f5f21b90ec45ba | train | class | class P2PLeakTest(KabberryTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-banscore='+str(banscore)]]
def run_test(self):
self.nodes[0].setmocktime(1501545600) # August 1st 2017
no_version_bannode = self.nodes[0].add_p2p_connection(CNodeNoVer... | class P2PLeakTest(KabberryTestFramework):
| def set_test_params(self):
self.num_nodes = 1
self.extra_args = [['-banscore='+str(banscore)]]
def run_test(self):
self.nodes[0].setmocktime(1501545600) # August 1st 2017
no_version_bannode = self.nodes[0].add_p2p_connection(CNodeNoVersionBan(), send_version=False)
no_... | ):
self.send_message(msg_verack())
def on_reject(self, message): pass
# Node that never sends a version. This one just sits idle and hopes to receive
# any message (it shouldn't!)
class CNodeNoVersionIdle(CLazyNode):
def __init__(self):
super().__init__()
# Node that sends a version but n... | 215 | 215 | 717 | 12 | 203 | Kozisto/kabb30 | test/functional/p2p_leak.py | Python | P2PLeakTest | P2PLeakTest | 92 | 150 | 92 | 92 | a87d4c5508fead0cbd4c4eca7af9e2c214b584e4 | bigcode/the-stack | train |
10446eb8fae3a514bd75bab6 | train | class | class CNodeNoVerackIdle(CLazyNode):
def __init__(self):
self.version_received = False
super().__init__()
def on_reject(self, message): pass
def on_verack(self, message): pass
# When version is received, don't reply with a verack. Instead, see if the
# node will give us a message tha... | class CNodeNoVerackIdle(CLazyNode):
| def __init__(self):
self.version_received = False
super().__init__()
def on_reject(self, message): pass
def on_verack(self, message): pass
# When version is received, don't reply with a verack. Instead, see if the
# node will give us a message that it shouldn't. This is not an exhau... | version. This one just sits idle and hopes to receive
# any message (it shouldn't!)
class CNodeNoVersionIdle(CLazyNode):
def __init__(self):
super().__init__()
# Node that sends a version but not a verack.
class CNodeNoVerackIdle(CLazyNode):
| 64 | 64 | 124 | 11 | 53 | Kozisto/kabb30 | test/functional/p2p_leak.py | Python | CNodeNoVerackIdle | CNodeNoVerackIdle | 77 | 90 | 77 | 77 | 1d8f9baa2e05635a50d18c3adc98cb8c2235550e | bigcode/the-stack | train |
e5d1dea240105716051bdbc3 | train | function | def processing_function(labels):
r,c = labels.shape
l = np.max(labels)+1
label_image = np.zeros((r,c,l))
for k in range(number_repetitions):
for i in range(1,l):
label_image[:,:,i] = (labels == i).astype(float)
D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patc... | def processing_function(labels):
| r,c = labels.shape
l = np.max(labels)+1
label_image = np.zeros((r,c,l))
for k in range(number_repetitions):
for i in range(1,l):
label_image[:,:,i] = (labels == i).astype(float)
D = km_dict.improb_to_dictprob(A, label_image, number_nodes, patch_size) # Dictionary
P = ... | branching_factor, number_training_patches, number_layers, normalization)
# Search km-tree and get assignment
A, number_nodes = km_dict.search_km_tree(image_float, T, branching_factor, normalization)
# number of repetitions for updating the segmentation
number_repetitions = 2
def processing_function(labels):
| 64 | 64 | 130 | 5 | 58 | Skielex/InSegt | pycode/demo_km.py | Python | processing_function | processing_function | 48 | 58 | 48 | 48 | 20d2a99aaab08893ce09890f99baa4778a3a13a9 | bigcode/the-stack | train |
0ea0bc64596fb047b07a8c4a | train | class | class YahooUtil:
def __init__(self):
self.logEnabled = configure.yahoo_logEnabled
def log(self, st, symbol):
if (self.logEnabled):
timediff = int((time.time() - st) * 1000)
logger.info(
'[YahooFinance] Time(ms):[%s] Symbol(s):[%s]',
timedi... | class YahooUtil:
| def __init__(self):
self.logEnabled = configure.yahoo_logEnabled
def log(self, st, symbol):
if (self.logEnabled):
timediff = int((time.time() - st) * 1000)
logger.info(
'[YahooFinance] Time(ms):[%s] Symbol(s):[%s]',
timediff, symbol)
... | # -*- coding: utf-8 -*-
import json
import logging
import ssl
import time
import urllib
import urllib.parse
import urllib.request
from qrcodeocr.common import configure
from qrcodeocr.util import utility
# import yahoo_finance as yf
# import pprint
logger = logging.getLogger(__name__)
ssl._create_default_https_conte... | 85 | 256 | 1,102 | 4 | 80 | Shihyen/ocr-test | qrcodeocr/util/yahooutil.py | Python | YahooUtil | YahooUtil | 20 | 138 | 20 | 20 | e7452b55fae56b22348b07880380291c6d6c4f41 | bigcode/the-stack | train |
b17aae7f17390e19142ddabe | train | function | def cholesky_numpy(M, cholesky):
"""Lower triangular version of a Cholesky decomposition of a posiive-definite M = L L^T
M must be symmetric, positive definite.
M is a numpy array"""
n = M.shape[0]
# Perform the Cholesky decomposition
for i in range(n):
for j in range(i+1):
... | def cholesky_numpy(M, cholesky):
| """Lower triangular version of a Cholesky decomposition of a posiive-definite M = L L^T
M must be symmetric, positive definite.
M is a numpy array"""
n = M.shape[0]
# Perform the Cholesky decomposition
for i in range(n):
for j in range(i+1):
val = M[i, j] - np.dot(c... | from math import sqrt
import numpy as np
#@profile
def cholesky_numpy(M, cholesky):
| 25 | 64 | 171 | 11 | 13 | pashminacameron/cholesky_benchmarking | python_cholesky/numpychol.py | Python | cholesky_numpy | cholesky_numpy | 5 | 20 | 5 | 5 | cbbc7f7df45ec728a60aa0d5db8268016cf92b5f | bigcode/the-stack | train |
af746bd019482350ee2660d7 | train | function | def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,
parse_record_fn, num_epochs=1, num_gpus=None,
examples_per_epoch=None):
"""Given a Dataset with raw records, return an iterator over the records.
Args:
dataset: A Dataset represent... | def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,
parse_record_fn, num_epochs=1, num_gpus=None,
examples_per_epoch=None):
| """Given a Dataset with raw records, return an iterator over the records.
Args:
dataset: A Dataset representing raw records
is_training: A boolean denoting whether the input is for training.
batch_size: The number of samples per batch.
shuffle_buffer: The buffer size to use when shuffling records. ... | layers. This
includes dataset management, hyperparameter and optimizer code, and argument
parsing. Code for defining the ResNet layers can be found in resnet_model.py.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
# pylint: disable=g-bad-i... | 197 | 197 | 657 | 36 | 160 | jovialio/models | official/resnet/resnet_run_loop.py | Python | process_record_dataset | process_record_dataset | 45 | 107 | 45 | 47 | e3b2bcdafe008bc789015ff14e8885be3dbba585 | bigcode/the-stack | train |
3c97373af0185efc7f46308b | train | function | def resnet_main(
flags_obj, model_function, input_function, dataset_name, shape=None):
"""Shared main loop for ResNet Models.
Args:
flags_obj: An object containing parsed flags. See define_resnet_flags()
for details.
model_function: the function that instantiates the Model and builds the
op... | def resnet_main(
flags_obj, model_function, input_function, dataset_name, shape=None):
| """Shared main loop for ResNet Models.
Args:
flags_obj: An object containing parsed flags. See define_resnet_flags()
for details.
model_function: the function that instantiates the Model and builds the
ops for train/eval. This will be passed directly into the estimator.
input_function: the ... | grad / loss_scale, var)
for grad, var in scaled_grad_vars]
minimize_op = optimizer.apply_gradients(unscaled_grad_vars, global_step)
else:
minimize_op = optimizer.minimize(loss, global_step)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
train_op = tf.group(m... | 256 | 256 | 1,065 | 21 | 235 | jovialio/models | official/resnet/resnet_run_loop.py | Python | resnet_main | resnet_main | 324 | 438 | 324 | 325 | 348091c462bfcf5cedb8b0010f7a88d6e82e59f5 | bigcode/the-stack | train |
8e002fb77ab34cf1270cc003 | train | function | def learning_rate_with_decay(
batch_size, batch_denom, num_images, boundary_epochs, decay_rates):
"""Get a learning rate that decays step-wise as training progresses.
Args:
batch_size: the number of examples processed in each training batch.
batch_denom: this value will be used to scale the base learni... | def learning_rate_with_decay(
batch_size, batch_denom, num_images, boundary_epochs, decay_rates):
| """Get a learning rate that decays step-wise as training progresses.
Args:
batch_size: the number of examples processed in each training batch.
batch_denom: this value will be used to scale the base learning rate.
`0.1 * batch size` is divided by this number, such that when
batch_denom == batch... | _dir, batch_size, *args, **kwargs): # pylint: disable=unused-argument
return model_helpers.generate_synthetic_data(
input_shape=tf.TensorShape([batch_size, height, width, num_channels]),
input_dtype=tf.float32,
label_shape=tf.TensorShape([batch_size]),
label_dtype=tf.int32)
retur... | 117 | 117 | 393 | 23 | 93 | jovialio/models | official/resnet/resnet_run_loop.py | Python | learning_rate_with_decay | learning_rate_with_decay | 140 | 174 | 140 | 141 | fd7029aea83dec07867cf552f3596e37795559ce | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.